css - Position Fixed Child 受位置相对父容器的 Z-index 限制
问题描述
定位固定元素总是相对于窗口定位自己。
但是,如果位置固定元素位于位置相对容器内,则位置固定子元素将遵循位置相对容器的 z-index。这意味着如果容器的任何兄弟姐妹也是相对的并且具有更高的 z-index,它们将覆盖位置固定的孩子。
示例:https ://jsfiddle.net/r4n6Lzhx/2/
<style>
.container1 {
position: relative;
z-index: 2;
height: 200px;
width: 100%;
background-color: yellow;
box-shadow: 5px 5px 3px #888888;
}
.container2 {
position: relative;
background-color: green;
z-index: 1;
height: 200px;
}
.overlay {
position: fixed;
top: 50px;
left: 50px;
right: 50px;
bottom: 50px;
background: black;
opacity: .8;
z-index: 3;
}
</style>
<div class="container1"></div>
<div class="container2">
<div class="overlay"></div>
</div>
有没有办法通过只更改孩子的 CSS 而不是父母的 CSS 来使位置固定的孩子“逃脱”父母的 z-index?
所需的最终结果是容器 1 覆盖容器 2,但覆盖层(即容器 2 的子级)覆盖容器 1,我无法更改容器 1 或容器 2 的 CSS。
解决方案
Setting container1 absolute and container2 relative will overlap them
z-index of container1 needs to be greater than the z-index of container2 and same for overlay and container1. Then if you doesn't set z-index of container2 it will be 0 and for container1 can be 1 and overlay 2.
I edited the width of container1 to see the container2 behind, you can set it back to 100%.
.container1 {
position: absolute;
z-index: 1;
height: 200px;
width: 90%;
background-color: yellow;
box-shadow: 5px 5px 3px #888888;
}
.container2 {
position: relative;
background-color: green;
height: 200px;
}
.overlay {
position: fixed;
top: 50px;
left: 50px;
right: 50px;
bottom: 50px;
background: black;
opacity: .8;
z-index: 2;
}
<div class="container1"></div>
<div class="container2">
<div class="overlay"></div>
</div>
推荐阅读
- python - 阅读 AVL 数据 TELTONIKA
- xml - 这个简单的 XML 有什么问题?
- typescript - 如何使用 Rollup.js 将绝对导入转换为相对导入?
- python - 如何设置 docker compose 以使用 ssh 通过 EC2 Bastion 连接到私有子网上的 AWS RDS
- c - 如何处理这种冲突的类型错误
- r - 将多图 ggplots 与拼凑和单个图例对齐
- mysql - 如何在 MySQL 上每天进行多表更新查询
- android - Android NDK 在线程内不打印
- javascript - 我是否走在构建在线游戏机器人的正确道路上?
- http - 像我五岁一样解释 - 网站检索文件、操作文件和返回文件