html - 相对位置如何使 dom 节点在固定位置上绘制?
问题描述
我正在构建一个模态,但在将背景保留在主要内容后面时遇到了问题。它们位于正确的层次结构上,以便正确绘制它们:后面的那些是第一位的。问题是绝对位置背景“隐藏”了内容,尽管内容应该画在后面,因此应该画在前面。
突然我意识到添加相对于内容的位置使它呈现在背景之上,所以背景的背景颜色不再“掩盖”它。
这是一个小提琴,您可以在其中看到绝对位置的内容如何具有正确的颜色,而具有正常位置的内容的颜色为红色。
.main {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
}
.background {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(100, 0, 0, 0.55);
}
.content {
background-color: lightblue;
padding: 1rem;
position: relative;
}
.norelative {
background-color: lightblue;
padding: 1rem
}
<div>
Just some basic text
</div>
<div class="main">
<div class="background"></div>
<div class="content">Content</div>
<div class="norelative">No relative</div>
</div>
https://jsfiddle.net/danielo515/x3u2Lth7/11/
这怎么可能?相对位置如何影响这个分层问题?
解决方案
这都是关于堆叠上下文的。使用position
不是static
(默认)的属性会使元素呈现在其他任何static
. 因此,您的背景呈现在静态非相对 div 之上,但由于相对 div 不是static
,它遵循正常呈现顺序并呈现在背景之上。
有关更多详细信息,请参阅堆叠上下文。
推荐阅读
- php - 我不明白为什么 PDO 插入 ' 代替单引号
- git - 如果我之前没有提交代码,我可以撤消合并吗?
- c# - 如何在 Swagger 中为 .Net Core 使用 @ApiImplicitParams?
- vue.js - GSAP:无法读取未定义的属性“样式”
- intellij-idea - 字符串比较挂在 IntelliJ 中用于大字符串
- python - ValueError:张量的形状 (26, 400) 与提供的形状 [26, 200] 不兼容
- r - 为不同的热图保持热图颜色范围相同
- c++ - 限制 Concurrency::parallel_for 中使用的线程数
- http - 如何阻止 ReverseProxy 代理请求
- android - 实施 Kapt 在自动生成的改造文件中导致构建错误