我有两个嵌套的CSS元素.我需要让父元素位于子元素的顶部,即z轴的上方.仅设置z-index是不够的.
我无法在子项上设置负z-index,它会将其设置为我实际页面上的页面容器下方.这是唯一的方法吗?
.parent {
position: relative;
width: 750px;
height: 7150px;
background: red;
border: solid 1px #000;
z-index: 1;
}
.child {
position: absolute;
background-color: blue;
z-index: 0;
color: white;
top: 0;
}
.wrapper
{
position: relative;
background: green;
z-index: 10;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="parent">
parent parent
<div class="child">
child child child
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
Ala*_*avi 72
z-index为子项设置负数,并删除父项上的一组.
.parent {
position: relative;
width: 350px;
height: 150px;
background: red;
border: solid 1px #000;
}
.parent2 {
position: relative;
width: 350px;
height: 40px;
background: red;
border: solid 1px #000;
}
.child {
position: relative;
background-color: blue;
height: 200px;
}
.wrapper {
position: relative;
background: green;
height: 350px;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="parent">parent 1 parent 1
<div class="child">child child child</div>
</div>
<div class="parent2">parent 2 parent 2
</div>
</div>Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/uov5h84f/
zie*_*lu1 52
幸运的是存在一个解决方案 您必须为父级添加包装器并更改此包装器的z-index(例如10),并将子级的z-index设置为-1:
.parent {
position: relative;
width: 750px;
height: 7150px;
background: red;
border: solid 1px #000;
z-index: initial;
}
.child {
position: relative;
background-color: blue;
z-index: -1;
color: white;
}
.wrapper {
position: relative;
background: green;
z-index: 10;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="parent">parent parent
<div class="child">child child child</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
其中一些答案确实有效,但设置position: absolute;并且z-index: 10;看起来非常强大,只是为了达到要求的效果.我发现以下是所有需要的,但不幸的是,我无法进一步减少它.
HTML:
<div class="wrapper">
<div class="parent">
<div class="child">
...
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
.wrapper {
position: relative;
z-index: 0;
}
.child {
position: relative;
z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)
我使用这种技术来实现图像链接的边界悬停效果.这里有更多的代码,但它使用上面的概念来显示图像顶部的边框.