gpt4 book ai didi

html - 为什么
的清除 float ?

转载 作者:技术小花猫 更新时间:2023-10-29 12:32:07 24 4
gpt4 key购买 nike

考虑以下测试用例,其中一个 float 元素和一个内联元素被放置在 <fieldset> 中。与 <div> :

.float {
float: right;
background-color: red;
height: 200px;
}
<h1>With fielset</h1>
<fieldset>
<span>Inline!</span>
<div class="float">Float!</div>
</fieldset>
<fieldset>
<span>Inline!</span>
<div class="float">Float!</div>
</fieldset>

<h1>With div</h1>
<div>
<span>Inline!</span>
<div class="float">Float!</div>
</div>
<div>
<span>Inline!</span>
<div class="float">Float!</div>
</div>

呈现时,fieldset容器有 200 像素高(它们会清除 float ?),而 div容器仅与行内元素一样高。此行为的原因是什么,是否有允许 fieldset 的解决方法?容器行为为 div容器呢?

最佳答案

显然 <fieldset>元素 are supposed to generate block formatting contexts for their contents :

The fieldset element is expected to establish a new block formatting context.

That's why floated elements don't float out of them.我猜想这与字段集作为可视化表单控制组的性质有关。可能还有其他原因,但在我的脑海中,这听起来是最合理的。

似乎没有办法撤销此操作,但我不会感到惊讶;您不能在创建 block 格式化上下文后将其销毁。


顺便说一下,<fieldset>不要清除 float (除非你给它们一个 clear 风格而不是 none )。当一个元素清除 float (或据说有间隙)时,它只会清除在相同格式上下文中接触它的 前面 float 。父元素也不会清除其子元素的 float ,但它可以为它们 float 建立格式化上下文。这是使用 <fieldset> 看到的行为。 , 当你设置 overflow 时也会发生这种情况到visible以外的东西在父元素上。

来自spec (强调我的):

This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box. The 'clear' property does not consider floats inside the element itself or in other block formatting contexts.

此外,如评论中所述,浏览器没有为该元素定义清除样式,因此默认清除样式已经是默认值none。 .这显示在这个演示中,其中只有一个 <fieldset> s 在 float 框被定义为具有清除属性之后出现,并且确实是清除 float 的那个。

.float {
float: right;
background-color: red;
height: 200px;
}

.clear {
clear: right;
}
<div class="float">Float!</div>
<fieldset>
<legend>Fieldset!</legend>
</fieldset>
<fieldset class="clear">
<legend>Clearing fieldset!</legend>
</fieldset>

External link of the demo

关于html - 为什么 <fieldset> 的清除 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6481944/

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