如何适合div的高度以包裹其漂浮的孩子 [英] How to fit a div's height to wrap around its floated children
问题描述
我的div包裹着两个孩子,一个漂浮在左边,另一个漂浮在右边.我想在孩子周围放置边框和背景,但div的高度为0,因为它的大小无法调整以适合孩子.
这里是一个实际的例子: http://jsfiddle.net/VVZ7j/17/
我希望红色背景一直下降.我已经尝试过height:auto,但这没用.
感谢您的任何帮助.
P.S.如果可能的话,我不想使用任何JavaScript.
在使用浮点数时,这是一个常见问题.有几种常见的解决方案,我已根据个人喜好排序(最好的方法在前):
-
使用:: after CSS伪元素.这就是所谓的"clearfix",并且可以在IE8及更高版本上运行.如果您需要与IE的早期版本兼容,请此答案应会帮助.示例.
.parentelement ::之后{内容: "";显示:表;清楚:两者;}
-
将两个浮点数添加到具有CSS属性
overflow:auto
或overflow:hidden
的容器中.但是,这种方法可能会引起问题(例如,当工具提示与父元素的边缘重叠时,将会出现滚动条).示例.< 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>
-
在浮点数后添加
clear:both 的div.示例.< div style ="float:left"></div>< div style ="float:left"></div>< div style ="clear:both"></div>
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.
Here is an example of it in action: http://jsfiddle.net/VVZ7j/17/
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.
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):
Use the ::after CSS pseudo element. This is know as the 'clearfix', and works IE8 and up. If you need compatibility with earlier versions of IE, this answer should help. Example.
.parentelement::after { content: ""; display: table; clear: both; }
Add the two floats into a container with the CSS attribute
overflow: auto
oroverflow: 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>
Add a set height to the parent element. Example.
<div style="height: 200px"> <div style="float: left"></div> <div style="float: left"></div> </div>
Make the parent element a float. Example.
<div style="float: left"> <div style="float: left"></div> <div style="float: left"></div> </div>
Add a div after the floats with
clear: both
. Example.<div style="float: left"></div> <div style="float: left"></div> <div style="clear: both"></div>
这篇关于如何适合div的高度以包裹其漂浮的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文