如何适应一个div的高度来包裹其漂浮的孩子 [英] How to fit a div's height to wrap around its floated children
问题描述
我有一个围绕两个孩子的div,一个浮动左边,另一个右边。我想把一个边框和背景围绕孩子,但div有0高度,因为它不调整大小适合孩子。
I have a div wrapped around two children, one floated left and the other right. I want to put a border and background around the children, but the div has 0 height since it doesn't resize to fit the children.
这是一个例子行动:
http://jsfiddle.net/VVZ7j/17/
我想要的红色背景一路走下去。我尝试了height:auto,但是没有效果。
I want the red background to go all the way down. I've tried height:auto, but that didn't work.
任何和所有的帮助将不胜感激。
Any and all help would be appreciated, thanks.
PS如果可能,我不想使用任何javascript。
P.S. I don't want to use any javascript if that's possible.
推荐答案
这是使用浮动广告时的常见问题。有几个常见的解决方案,我已经排序的个人偏好(最好的方法第一):
This is a common issue when working with floats. There are several common solutions, which I have ordered by personal preference (best approach first):
.parentelement::after {
content: "";
display: table;
clear: both;
}
将两个浮动广告添加到CSS属性< c $ c> overflow:auto 或 overflow:hidden
。然而,这种方法可能导致问题(例如,当工具提示与父元素的边缘重叠时,滚动条将出现)。 示例。
Add the two floats into a container with the CSS attribute overflow: auto
or overflow: hidden
. However, this approach can cause issues (e.g. when a tooltip overlaps the edges of the parent element a scrollbar will appear). Example.
<div style="overflow: auto">
<div style="float: left"></div>
<div style="float: left"></div>
</div>
向父元素添加设置高度。 示例。
<div style="height: 200px">
<div style="float: left"></div>
<div style="float: left"></div>
</div>
将父元素设为浮动。 示例。
<div style="float: left">
<div style="float: left"></div>
<div style="float: left"></div>
</div>
在浮动后添加一个div code>。 示例。
<div style="float: left"></div>
<div style="float: left"></div>
<div style="clear: both"></div>
这篇关于如何适应一个div的高度来包裹其漂浮的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!