When utilizing position:fixed
and positioning your :before
element 150px from the top and 150px from the left, it is expected that it will appear 'after' your .box
element. This is because the .box
is 100px wide and 100px tall, positioned 100px from the left and 100px from the top, also with a fixed position.
If you switch to using position:absolute
on the :after
element, it will be positioned relative to its parent div. Here's an example:
.box {
position: fixed;
width: 100px;
height: 100px;
top: 100px;
left: 100px;
background-color: yellow;
border: 10px solid green;
z-index: 1;
}
.box:before {
content: '';
position: absolute;
width: 100px;
height: 100px;
top: 0px;
left: -110px;
background-color: tomato;
z-index: -1;
}
<div class="box"></div>
Edit: In response to Amaury Hanser's comment, I have included a second snippet for positioning the :before
"below" the .box
, in terms of z-index
:
.box:before {
content: '';
position: fixed;
width: 100px;
height: 100px;
top: 100px;
left: 100px;
background-color: yellow;
border: 10px solid green;
z-index: 1;
}
.box:after {
content: '';
position: absolute;
width: 300px;
height: 300px;
top: 150px;
left: 150px;
background-color: tomato;
z-index: 0;
}
<div class="box"></div>
Simply put, consider pseudo-elements as similar to child/parent elements. A child element cannot have a z-index lower than the parent unless the parent has no z-index assigned. Additionally, certain position
CSS rules have default z-index values, preventing children from going behind their parents.