我想要一个元素 (div
) 在其固定父元素 (header
) 下分层:
header {
position: fixed;
width: 100%;
height: 100px;
background-color: #ccc;
}
header > div {
position: absolute;
height: 100%;
width: 100px;
z-index: -1;
transform: translateY(50%);
background-color: #aaa;
}
<header>
<div>
</div>
</header>
这在 Firefox 中有效,但在 Chrome 中无效。要修复它,您需要这样做:
header {
position: fixed;
width: 100%;
height: 100px;
}
header > div {
position: relative;
width: 100%;
height: 100%;
background-color: #ccc;
}
header > div > div {
position: absolute;
height: 100%;
width: 100px;
z-index: -1;
transform: translateY(50%);
background-color: #aaa;
}
<header>
<div>
<div>
</div>
</div>
</header>
但这很糟糕! 根据规范,Firefox 或 Chrome 谁错了?是否有更好的方法来跨浏览器完成这项工作?
最佳答案
试试这个,
header {
position: fixed;
width: 100%;
height: 100px;
background-color: #ccc;
overflow: hidden;
}
header > div {
height: 100%;
z-index: -1;
transform: translateY(50%);
background-color: #aaa;
overflow: hidden;
}
<header>
<div></div>
</header>
看来我误解了你的问题。无论如何,答案是 chrome 是正确的。我认为更好的解决方案是使用相同级别的两个 DIV(如果可能)。
header {
position: fixed;
width: 100%;
overflow: hidden;
}
header .header-inner {
position: relative;
height: 100px;
width: 100%;
z-index: 1;
background-color: #ccc;
}
header .under-layer {
position: absolute;
height: 100%;
z-index: -1;
transform: translateY(50%);
background-color: #aaa;
overflow: hidden;
top: 0px;
width: 100%;
}
<header>
<div class="header-inner"></div>
<div class="under-layer"></div>
</header>
关于html - 在 Chrome 中使用 `z-index` 的固定父元素下的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31415727/