我有一个包裹着两个 child 的 div,一个向左浮动,另一个向右浮动。我想在 child 周围放置边框和背景,但 div 的高度为 0,因为它不会调整大小以适合 child 。
这是一个实际的例子: http://jsfiddle.net/VVZ7j/17/
我希望红色背景一直向下。我试过 height:auto,但没用。
我们将不胜感激,谢谢。
附言如果可能的话,我不想使用任何 javascript。
最佳答案
这是使用 float 时的常见问题。有几种常见的解决方案,我根据个人喜好排序(最佳方法优先):
使用::after CSS 伪元素。这被称为“clearfix”,适用于 IE8 及更高版本。如果您需要与早期版本的 IE 兼容,this answer should help . Example .
.parentelement::after { content: ""; display: table; clear: both; }
将这两个 float 添加到具有 CSS 属性
overflow: auto
或overflow: hidden
的容器中。但是,这种方法可能会导致问题(例如,当工具提示与父元素的边缘重叠时,将出现滚动条)。 Example .<div style="overflow: auto"> <div style="float: left"></div> <div style="float: left"></div> </div>
给父元素添加一个设置的高度。 Example .
<div style="height: 200px"> <div style="float: left"></div> <div style="float: left"></div> </div>
将父元素设为 float 。 Example .
<div style="float: left"> <div style="float: left"></div> <div style="float: left"></div> </div>
使用
clear: both
在 float 后添加一个 div。 Example .<div style="float: left"></div> <div style="float: left"></div> <div style="clear: both"></div>
关于html - 如何调整 div 的高度以包裹其 float 的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10969023/