gpt4 book ai didi

html - block 元素如何在 float 的 div 中工作?

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:39 25 4
gpt4 key购买 nike

这是以下问题的延续:

CSS Float - The content stays in the default stack position

当我在 box1 中添加一个 block 元素(p 元素)(在 float 的 box0 之后)时,p 元素按预期换行。但是,它不是从容器的边缘开始的。请看图片。

此外,当我将 display: inline-block、float:left 或 overflow:hidden 添加到段落元素时,行为也不同。有人可以解释这些情况吗?

enter image description here

http://jsfiddle.net/jintoppy/xGm5E/3/

<div class="box0">Box 0</div>
<div class="box1">Box1 should wrap with text elements.
<p>But, what about block elements? Why it is behaving like this</p>
</div>

.box0 {
width: 100px;
height: 100px;
background-color: green;
float: left;
opacity: .5;
}
.box1 {
width: 200px;
height: 100px;
background-color: red;
}
p {
border: 1px solid #000;
}

最佳答案

p 中的文本空间不足在那里开始一条新线,所以它只从 float 的右边缘开始,在 float 下方出现一个间隙。如果你给 p上边距稍大,there will be enough room for the second line of text to start directly underneath the float :

p {
margin-top: 1.2em;
border: 1px solid #000;
}

您也可以像其他人提到的那样增加行高;这将使第一行足够高,以便第二行有空间从 float 下方开始。

之所以p的界限|元素没有完全移出 float 是因为 p元素的行为与 .box1 完全相同,因为它们都没有 float 。文本换行方式与我在 my previous answer 中描述的方式相同.


添加 display: inline-block 时它表现不同的原因, float: leftoverflow: hidden在我之前回答的评论中给出:

overflow: hidden causes the box to generate a block-formatting context, which makes it immune to surrounding floats. That causes the entire box to shift outside of the float and sit right next to it instead.

(从技术上讲,display: inline-block 也会使 p 元素本身充当内联元素,换句话说,它像 .box1 中的第一句话一样内联呈现,但这具有相同的效果。)

当两者都不是.box1也不p正在生成 block 格式化上下文,它们都参与相同的上下文,这实际上是根元素的上下文。这就是导致它们以您所观察到的方式与漂浮物互动的原因。

block 格式化上下文是一个非常复杂和广泛的主题,我不想自己深入,但是 this question 的答案对它们如何工作以及元素如何在各种情况下与周围的元素相互作用进行了很好的视觉解释。

关于html - block 元素如何在 float 的 div 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23624372/

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