gpt4 book ai didi

html - CSS 负边距重叠不适用于子元素

转载 作者:行者123 更新时间:2023-12-02 04:06:29 26 4
gpt4 key购买 nike

我正在努力解决一些基本的 CSS 布局流程。如果我依次有两个 div,其中第二个 div 的上边距为负,我希望它与前一个 div 重叠。

但是,我发现虽然第一个 div 确实重叠,但它的内容却没有。

<div style="background:green;height:20px;">
<span style="background:red;display:inline-block;padding:2px;">HELLO</span>
<span style="background:red;display:inline-block;padding:2px;">HELLO</span>
<span style="background:red;display:inline-block;padding:2px;">HELLO</span>
</div>
<div style="background:yellow;height:20px;margin-top:-10px;">
</div>

enter image description here

https://jsfiddle.net/xwghd5r2/


这似乎违背了基本堆叠顺序的原则:

来自https://css-tricks.com/almanac/properties/z/z-index/ :

Without any z-index value, elements stack in the order that they appear in the DOM (the lowest one down at the same hierarchy level appears on top). Elements with non-static positioning will always appear on top of elements with default static positioning.

Also note that nesting plays a big role. If an element B sits on top of element A, a child element of element A can never be higher than element B.


注意:我并不是通过更改 position 属性来寻求修复 - 我只是想了解为什么默认静态会发生此电流流定位。

最佳答案

绘制顺序在Appendix E中定义。 .

当浏览器绘制这些内容时,它会首先绘制 block 的背景

  1. For all its in-flow, non-positioned, block-level descendants in tree order: If the element is a block, list-item, or other block equivalent:

    1. background color of element.

内联 block 的背景将绘制在 block 的背景前面:

  1. Otherwise: first for the element, then for all its in-flow, non-positioned, block-level descendants in tree order:

    1. Otherwise, for each line box of that element:

      1. For each box that is a child of that element, in that line box, in tree order:

        1. background color of element.

请注意,第二个 block 的内容仍将绘制在内联 block 的前面:

div {
height: 20px;
background: green;
}
div + div {
background: yellow;
margin-top: -10px;
color: #0ff;
}
span {
background: red;
display: inline-block;
padding: 2px;
}
<div>
<span>HELLO</span>
<span>HELLO</span>
<span>HELLO</span>
</div>
<div>█ █ █ █ █ █ █ █ █</div>

关于html - CSS 负边距重叠不适用于子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39212659/

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