Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Z-index with before pseudo-element

Tags:

I've created a 'header' element with a before-pseudo element. the pseudeo element must be behind the parent element. Everything works great till the moment I give my 'header' a z-index.

What I want: The yellow 'header' on the foreground, the red pseudo-element in the background and a simple z-index of 30 on the yellow 'header' element.

header {      background: yellow;     position:relative;     height: 100px;     width: 100px;     z-index:30; /*This is the problem*/ }  header::before {      content:"Hide you behind!";     background: red;     position:absolute;     height: 100px;     width: 100px;     top:25px;     left:25px;     z-index:-1; } 

You can test my problem on this link (http://jsfiddle.net/tZKDy/) and you see the problem when you set/remove the z-index on de 'header' element.

like image 450
Tom Claus Avatar asked Oct 19 '11 13:10

Tom Claus


People also ask

Does Z-Index working on pseudo-element?

It is important to realize that pseudo-elements are considered descendants of their associated element. You may set a negative z-index for these pseudo-elements, but in order for them to actually appear below their parent element, you must create a new stacking context for the parent.

What can you do with the before pseudo-element?

The ::before pseudo-element can be used to insert some content before the content of an element.

Why Z-index is not working in before?

z-index only works on positioned elements (relative, absolute, fixed, sticky) so if you set a z-index on an element with a static position, it won't work.

Is there a class before pseudo?

::before (:before) In CSS, ::before creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.


2 Answers

The ::before pseudo-element is placed inside the header element.

CSS Spec:

The :before and :after pseudo-elements interact with other boxes as if they were real elements inserted just inside their associated element.

Setting the z-index for the header element creates a new Stacking Context, so the new pseudo element you created can not float behind the header element, because it would have to go outside that Stacking Context.

I suggest that you simply precede the header element by another element, so it stacks correctly by default. Example.

like image 76
RC-1290 Avatar answered Sep 21 '22 21:09

RC-1290


I used z-index:-1 (enter link description here)

a {     position: relative;     z-index: 1;     text-align: center;     display: table-cell;     vertical-align: middle;      &::before {         content: "";         position: absolute;         top: 0;         bottom: 0;         left: 0;         right: 0;         background-color: $secondryColor;         z-index: -1;     }    } 
like image 40
Velihan Kara Avatar answered Sep 22 '22 21:09

Velihan Kara