gpt4 book ai didi

html - CSS 定位 : Relative influences stacking order without z-index

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:21 24 4
gpt4 key购买 nike

我遇到了一些我找不到解释的奇怪的 CSS。

使用 position: absolute,一个 div a 被拉到另一个 div b。当 div b(位于 a 下方)有一个 position: relative 的子元素时,该元素出现在 上方>一个

var parent = document.querySelector('.parent')

document.querySelector('button').addEventListener('click', function() {
parent.classList.toggle('toggle-class')
});
.parent {
background: grey;
height: 100px;
position: relative;
}

.child-a {
background: orange;
position: absolute;
width: 100%;
height: 100%;
text-align: center;
}

.child-b {
background: green;
height: 100%;
}

.toggle-class .child-b span {
position: relative;
}
<div class="parent">
<div class="child-a">
child a
</div>
<div class="child-b">
<span>child b' child</span>
</div>
</div>

<button>
toggle
</button>

我的第一 react 是阅读堆栈上下文,但由于没有 z-index 在起作用,这可能与定位有关。尽管如此,我还是不明白这是怎么可能的——为什么在应用 position: relative 时元素会出现在上方?

最佳答案

这是因为堆栈上下文。请注意,构成堆叠上下文的不仅仅是 z-index 值。定位元素也是如此。所以 .parent 创建了一个堆栈上下文,因为它是 relative 定位的。切换后,.child-b 范围将相对于 .parent 定位。

参见 MDN Web Docs

关于html - CSS 定位 : Relative influences stacking order without z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47243827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com