同一元素的文本和背景之间的图层



我在CSS中遇到过这种情况,以前从未见过,其中一个元素位于另一个元素的背景和文本之间。我知道这里发生的事情不是最佳实践(元素大于其给定的高度(,但为了进一步了解CSS知识,我有兴趣了解到底发生了什么(在堆叠上下文等方面(:

.search {
width: 2rem;
height: 10rem;
background: red;
margin-left: 2rem;
}
.header__top {
display: flex;
height: 2rem;
background: blue;
}
.header__bottom {
font-size: 2rem;
background: green;
}
<div class="header__top"><div class="search"></div></div>
<div class="header__bottom">Hello!</div>

从理论上讲,任何与没有给定z索引的堆叠相关的事情(就像这里的情况一样(都应该在没有z索引属性的堆叠中描述,但我找不到这里提到的情况。

编辑

我不知道这是否奇怪,但我发布这样的问题并不是为了得到解决方案(在这种情况下有很多(,而是因为我想更好地理解CSS的理论。我的目标是看到一些CSS代码,并知道它将如何呈现。每当发生一些事情,我无法用我迄今为止学到的东西来解释(堆叠上下文、盒子模型等(,并且我找不到一些文件来解释这些现象背后的理论时,我就会把它发布在某个地方。

红色面板显示在绿色面板下,因为绿色面板没有位置定义,所以它采用默认值static,在这种情况下,不应用z索引规则

https://developer.mozilla.org/fr/docs/Web/CSS/z-index

你可以使用一个相对的位置让绿色面板在红色面板之上

.search {
width: 2rem;
height: 10rem;
background: red;
margin-left: 2rem;
}
.header__top {
display: flex;
height: 2rem;
background: blue;
}
.header__bottom {
font-size: 2rem;
background: green;
position: relative
}
<div class="header__top">
<div class="search"></div>
</div>
<div class="header__bottom">Hello!</div>

最新更新