最佳答案
块格式化上下文是如何工作的?
CSS2.1规范指出,在块格式化上下文中,框是垂直布局的,从顶部开始。除非块框建立了一个新的块格式化上下文,否则即使存在浮动元素,也会发生这种情况。众所周知,当浏览器在块格式化上下文中呈现块框时,会省略浮动元素,为什么建立一个新的块格式化上下文会起作用呢?
盒子(块盒子和内联盒子)是如何在正常流程中布局的?
我在某处读到过,块元素生成块框,但是当用户代理绘制框时忽略浮动元素,并且在填充内容时考虑浮动元素。虽然浮动元素将重叠其他元素的框边界,但解决方案是使用 overflow:hidden
为重叠元素建立一个新的块格式化上下文。
“新的块格式化上下文仍然是块格式化”,因此当绘制一个框时,它也会将浮动元素视为没有退出。是这样还是我误解了“新块格式化上下文”
通过说“正是这种行为对柱状样式布局很有用。然而,它的主要用途是停止浮动,比如在“ main content”div 中,实际上是清除浮动的侧列,即源代码中早期出现的浮动
我不明白的意思,我会提供一个例子,也许你会理解我。
.content {
background: #eee;
color #000;
border: 3px solid #444;
width: 500px;
height: 200px;
}
.float {
background: rgba(0, 0, 255, 0.5);
border: 1px solid #00f;
width: 150px;
height: 150px;
float: right;
}
p {
background: #444;
color: #fff;
}
<div class="content">
<h3>This is a content box</h3>
<p>It contains a left floated box, you can see the actual content div does go under the float, but that it is the <h3> and <p> <b>line boxes</b> that are shortened to make room for the float. This is normal behaviour.</p>
<div class="float">floated box</div>
</div>
我认为浮动框应该浮动到包含块的顶部-类 content
的 div。此外,如果浮动框出现在标记的前面,那么它将显示我认为应该出现的内容。
.content {
background: #eee;
color #000;
border: 3px solid #444;
width: 500px;
height: 200px;
}
.float {
background: rgba(0, 0, 255, 0.5);
border: 1px solid #00f;
width: 150px;
height: 150px;
float: right;
}
p {
background: #444;
color: #fff;
}
<div class="content">
<div class="float">floated box</div>
<h3>This is a content box</h3>
<p>it contains a left floated box, you can see the actual content div does go under the float, but that it is the <h3> and <p> <b>line boxes</b> that are shortened to make room for the float, this is normal behaviour</p>
</div>
我们如何解释呢? 我们可以用“块格式化上下文和内联格式化上下文”来解释吗?