Reputation: 870
This doesn't make sense to me. Shouldn't ::before get rendered before the span? It works if I add position:relative to the child element.
This could have something to do with the stacking context, but I'm not sure how exactly.
https://www.w3.org/TR/CSS21/visuren.html#layers
The span in this case falls in #3 because it's non-positioned and ::before #6 because it's a positioned descendant?
div { position:relative; }
div:before {
content: '';
width: 100%;
height: 100%;
background: red;
position: absolute;
top: 0;
left: 0;
}
/* Adding this works: */
/* span { position: relative; } */
<div>
<span>Test</span>
</div>
Upvotes: 2
Views: 844
Reputation: 1980
You can set z-index to -1 nowadays to make it appear below all children.
Upvotes: 1
Reputation: 1657
How :pseudo
CSS class works is the element will be added before and within the element.
like so:
<div>
:before
<span>Test</span>
</div>
I'm not very what you need to achieve but to explain your doubt, the reason you are producing the current outcome after adding position:relative
to your div is because :before
is set with position:absolute
. By doing so it will pull the :before element out of the current html hierarchy and position itself relative to the nearest element where you set div { position:relative; }
.
Since the before is being pulled out of the hierarchy the <span>
will fill up the empty space available (aka overlapped by :before).
Upvotes: 0
Reputation: 538
If an item doesn't have position
set, then it's set pretty low in the layout. If you position any element as absolute
you should give some position
to all the sibling elements. In this example ::before
and span
are siblings, and since ::before
has position and span
doesn't ::before
is more "important"
Upvotes: 4
Reputation: 7692
Since you specified that position is absolute
it makes content to be in another flow level. You can try to specify z-index
, however even that not always works. For example if you have some element with absolute/relative
positioning it will be over static
with any number of z-index.
Upvotes: 1