To answer your question, you need to understand concepts like z-index
and/or how the stacking order works. There are great articles that will explain z-index, but one in particular I really enjoy is What no one told you about z-index.
A snippet from the referenced article above:
When you introduce the position property into the mix, any positioned elements (and their children) are displayed in front of any non-positioned elements. (To say an element is “positioned” means that it has a position value other than static, e.g., relative, absolute, etc.)
Interestingly enough, there's a CSS3 property that does something similar. You can address your issue, without the need of explicitly applying a z-index, by using transform
.
For example, if we apply transform: translateX(0)
to your JSFiddle, you'll see that the gray div now sits above your text. Here's an updated fiddle:
https://jsfiddle.net/gh94Lbad/
<div style="width:auto; height:50px; background-color:grey; transform: translateX(0)"></div>
<div style="width:auto; height:350px; background-color:grey;transform: translateX(0)">I want to be in displayed in front</div>
The reason transform
works (by modifying the stacking context) is explained in the spec:
For elements whose layout is governed by the CSS box model, any value other than none for the transform property results in the creation of a stacking context. Implementations must paint the layer it creates, within its parent stacking context, at the same stacking order that would be used if it were a positioned element with z-index: 0. If an element with a transform is positioned, the z-index property applies as described in [CSS2], except that auto is treated as 0 since a new stacking context is always created.
Edit: As pointed out by @TemaniAfif, it's probably better to explain how this works by explaining the paint order
of your elements:
For this you need to consider the painting order (w3.org/TR/css-position-3/#painting-order) where you find that transformed element are painted later thus they are above. (in the step (8) )