有没有办法以这种方式操纵堆叠上下文?我希望文本位于蓝色元素的顶部。
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>
是否有任何通配符或类似 !important
的东西可以覆盖堆栈上下文?做到这一点的唯一方法是让文本成为一个独立的元素?
最佳答案
是的,你可以,诀窍是让红色元素保持 z-index:auto
这样 p
就不会属于它的堆叠上下文,可以放在上面蓝色元素。
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
不要忘记使 p
定位以便能够使用 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>
您也可以删除所有内容,只玩 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>
您可以引用这个问题(Strange behavior of background when elements are overlapping)来了解它是如何工作的。
关于html - 较低的 z-index 父子元素位于较高的 z-index 元素之上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51314926/