Reputation: 3705
Is there a way to manipulate the stacking context this way? I want the text to be on the top of the blue element.
div{
width: 200px;
height: 200px;
position: absolute;
}
#a{
z-index: 0;
background-color: red;
left: 150px;
top: 150px;
}
#b{
z-index: 1;
background-color: blue;
left: 0;
top: 0;
}
p{
z-index: 2;
}
<div id="a">
<p>verylongtext</p>
</div>
<div id="b"></div>
Is there any wild card or something like !important
which can override the stacking context? The only way to do this is make the text an independent element?
Upvotes: 3
Views: 88
Reputation: 273011
Yes you can, the trick is to keep the red element with z-index:auto
so that p
will not belong to its stacking context and can be placed above the blue element.
auto
The box does not establish a new local stacking context. The stack level of the generated box in the current stacking context is the same as its parent's box.ref
Don't forget to make the p
positioned in order to be able to use z-index
:
div {
width: 200px;
height: 200px;
position: absolute;
}
#a {
background-color: red;
left: 150px;
top: 150px;
}
#b {
z-index: 1;
background-color: blue;
left: 0;
top: 0;
}
p {
z-index: 2;
position: relative;
}
<div id="a">
<p>verylongtext</p>
</div>
<div id="b"></div>
You can also remove everything and play only with margin:
div {
width: 200px;
height: 200px;
}
#a {
background-color: red;
margin-left: 150px;
margin-top: 150px;
overflow:hidden; /*remove margin-collapsing*/
}
#b {
background-color: blue;
margin-top: -350px;
}
<div id="a">
<p>verylongtext</p>
</div>
<div id="b"></div>
You can refer to this question ( Strange behavior of background when elements are overlapping) to understand how it works.
Upvotes: 2
Reputation: 42304
It is unfortunately impossible to break the stacking context in this way, as a child's z-index
is set to the same stacking index as its parent. You will need to make the text a sibling element, and additionally make sure it has a position
other than static
in order for the z-index
to apply.
From here, it's a simple matter of positioning it as desired (in this case with top: 150px
and left: 150px
.
This can be seen in the following:
div {
width: 200px;
height: 200px;
position: absolute;
}
#a {
z-index: 0;
background-color: red;
left: 150px;
top: 150px;
}
#b {
z-index: 1;
background-color: blue;
left: 0;
top: 0;
}
p {
position: absolute;
z-index: 2;
top: 150px;
left: 150px;
}
<div id="a"></div>
<div id="b"></div>
<p>verylongtext</p>
Upvotes: 0