html - 你如何防止 float 元素的 parent 崩溃?

标签 html css layout css-float clearfix

<分区>

尽管像 <div> 这样的元素通常使用 float 来适应它们的内容。属性可能会给 CSS 新手带来一个令人吃惊的问题:如果 float 元素有非 float 父元素,父元素会折叠。

例如:

<div>
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

本例中的父 div 将不展开以包含其 float 的子元素 - 它看起来有 height: 0 .

你是如何解决这个问题的?

我想在这里创建一个详尽的解决方案列表。如果您知道跨浏览器兼容性问题,请指出。

方案一

float 父对象。

<div style="float: left;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

优点:语义代码。
缺点:您可能并不总是希望父级 float 。就算你做了,你 float parent 的 parent ,等等?必须 float 每个祖先元素吗?

解决方案2

给 parent 一个明确的高度。

<div style="height: 300px;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

优点:语义代码。
缺点:不灵活 - 如果内容更改或浏览器调整大小,布局将会中断。

方案三

在父元素中附加一个“间隔”元素,像这样:

<div>
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
  <div class="spacer" style="clear: both;"></div>
</div>

优点:直接编码。
缺点:没有语义; spacer div 仅作为布局 hack 存在。

解决方案4

将父级设置为 overflow: auto .

<div style="overflow: auto;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

优点:不需要额外的 div。
缺点:看起来像是一个 hack - 那不是 overflow属性(property)的既定用途。

评论?其他建议?

最佳答案

解决方案一:

最可靠和不引人注目的方法似乎是这样的:

演示:http://jsfiddle.net/SO_AMK/wXaEH/

HTML:

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>​

CSS:

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
}

通过一些 CSS 定位,您甚至不需要向父级 DIV 添加类。

此解决方案向后兼容 IE8,因此您无需担心旧版浏览器出现故障。

方案二:

已建议对解决方案 1 进行改编,如下所示:

演示:http://jsfiddle.net/wXaEH/162/

HTML:

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>​

CSS:

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
   *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML += '<div class="ie7-clear"></div>' );
}

.ie7-clear {
    display: block;
    clear: both;
}

此解决方案似乎向后兼容 IE5.5,但未经测试。

解决方案 3:

也可以设置 display: inline-block;width: 100%; 来模拟一个普通的 block 元素而不折叠。

演示:http://jsfiddle.net/SO_AMK/ae5ey/

CSS:

.clearfix {
    display: inline-block;
    width: 100%;
}

该方案应该向后兼容 IE5.5,但只在 IE6 中测试过。

关于html - 你如何防止 float 元素的 parent 崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080240/

上一篇:c# - 在网页中显示的语法

下一篇:jquery - 阻止父元素触发事件的子元素

相关文章:

javascript - 突出显示 Three.js 中的 THREE.Line

javascript - 将 HTML DOM 元素转换为 JavaScript 对象?

javascript - 无法从动态填充的字符串中 trim 尾随逗号

android - 结合搜索栏和进度条来创建支持修剪的媒体播放器

java - 用户自定义布局的更简单方法

html - CSS 下拉菜单仅显示 ul 而不是 ie9 中的元素

css - 小宽度的破损按钮

jquery - Bootstrap toast 组件无法在数据表上正常工作

css - 如何在电子邮件中使用图像作为表格背景?

android - 在 ImageView 上设置负边距会移动 ImageView 而不是 Image