如何将蓝色 div 覆盖在黄色 div 上?我试图给外部 div 添加一个相对位置,但我没有工作。
.c1{
padding:25px;
background: blue;
position: relative;
top: 0;
left: 0;
z-index: 10;
}
.c2{
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
background: yellow;
}
<div class="container">
<div class="c1">
<div class="c2">
Hallo Welt
</div>
</div>
</div>
你可以在他的父元素后面有一个带有 z-index 的子元素。你必须把
z-index:-1;
和position:absolute;
给孩子div.
我还分享了一篇文章的链接供您参考,该文章描述了如何使用元素的堆叠顺序来允许 z-index 为负,以便将元素放在其父元素后面。 没有人告诉您关于 Z-Index 的事
.c1{
padding:25px;
background:blue;
position:relative;
top: 0;
left: 0;
}
.c2{
position:absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: yellow;
z-index:-1;
}
<div class="container">
<div class="c1">
<div class="c2">
Hallo Welt
</div>
</div>
</div>
根据 CSS 规范,当使用
position: absolute
值时,元素将始终寻找定位的父元素(即带有 position: relative
的元素)作为参考点。如果找不到定位的父元素,该元素将默认为文档主体。
此外,在使用
position
属性时,z-index
属性仅适用于定位元素(即位置值不是 static
的元素)。
.c1 {
padding: 25px;
background: blue;
position: relative;
top: 0;
left: 0;
z-index: 10;
}
.c2 {
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
background: yellow;
position: absolute;
}
<div class="container">
<div class="c1">
<div class="c2">
Hallo Welt
</div>
</div>
</div>