首页 > 解决方案 > 相对位置如何使 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/

这怎么可能?相对位置如何影响这个分层问题?

标签: htmlcss

解决方案


这都是关于堆叠上下文的。使用position不是static(默认)的属性会使元素呈现在其他任何static. 因此,您的背景呈现在静态非相对 div 之上,但由于相对 div 不是static,它遵循正常呈现顺序并呈现在背景之上。

有关更多详细信息,请参阅堆叠上下文


推荐阅读