14

考虑以下测试用例,其中浮动元素和内联元素放置在 a<fieldset>与 a 中<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 像素(它们清除浮动?),而div容器仅与内联元素一样高。这种行为的原因是什么,是否有一种解决方法可以让fieldset容器像div容器一样运行?

4

2 回答 2

19

显然<fieldset>元素应该为其内容生成块格式化上下文

fieldset元素应建立一个新的块格式化上下文。

这就是为什么浮动元素不会浮出它们的原因。我猜这与字段集作为视觉表单控制组的性质有关。可能还有其他原因,但在我看来,这听起来最合理。

似乎没有办法撤消这一点,但我不会感到惊讶;创建块格式上下文后,您无法销毁它。


顺便说一句,<fieldset>s 不清除浮动(除非你给他们一种clear风格以外的东西none)。当一个元素清除浮动(或者说有清除)时,它只清除在相同格式上下文中接触它的前面的浮动。父元素也不会清除其子元素的浮动,但它可以为它们建立浮动格式上下文。这是使用 看到的行为,当您设置为父元素以外的其他<fieldset>内容时也会发生这种情况。overflowvisible

规范(强调我的):

此属性指示元素框的哪些边可能与较早的浮动框相邻。'clear' 属性不考虑元素本身或其他块格式上下文中的浮动。

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

.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>

演示的外部链接

于 2011-06-26T03:58:10.263 回答
-1

设置包装器 div 的高度;

 <html>
 <head>    
  <style type="text/css">       
   .float {float:right; background-color:red;             height:200px;}   
</style> 
 </head> 
 <body>    
 <fieldset>    
   <span>Inline!</span>    
   <div class="float">Float!</div>  
 </fieldset> 
 <fieldset>     
    <span>Inline!</span>      
   <div class="float">Float!</div>
 </fieldset> 

  <div style="height:200px">    
   <span>Inline!</span>     
  <div class="float">Float!</div> </div> 
 <div style="height:200px">     
 <span>Inline!</span>    
 <div class="float">Float!</div> 
</div>
</body>
</html> 
于 2011-06-26T04:00:27.053 回答