How do I get a div to wrap around floating children?
Solution 1
Most of the time, adding overflow:hidden
on the wrapper is sufficient:
<div style="border:1px solid #000; overflow:hidden;">
<span style="float:left">Content</span>
<span style="float:left">Content</span>
<span style="float:left">Content</span>
</div>
Sometimes, you'll see this alternate approach (which is much more hacky, but probably has better back-version browser support).
<div style="border:1px solid #000; ">
<span style="float:left">Content</span>
<span style="float:left">Content</span>
<span style="float:left">Content</span>
<div style="clear:both;"></div>
</div>
Solution 2
Use the clear CSS property according to MDN web docs: https://developer.mozilla.org/en-US/docs/Web/CSS/clear
Note: If an element contains only floated elements, its height collapses to nothing. If you want it to always be able to resize, so that it contains floating elements inside it, you need to self-clear its children. This is called clearfix, and one way to do it is clear a replaced ::after pseudo-element on it.
#container::after { content: ""; display: block; clear: both; }
Related videos on Youtube
Comments
-
Moshe almost 2 years
Considering the following code, where the
span
elements are floating inside of thediv
, how can I make thediv
wrap around the floating child elements, so that the 1px border wraps the children elements?<div style="border:1px solid #000"> <span style="float:left">Content</span> <span style="float:left">Content</span> <span style="float:left">Content</span> </div>
-
Moshe over 13 yearsThanks, the hack is better for IE6 and such?
-
TehOne over 13 yearsJust to post a follow-up, this is usually taken care of by using a "clearfix". You can see more information here: webtoolkit.info/css-clearfix.html
-
Lee over 13 years@TehOne: "clearfix" works on the same principle as the
clear:both
div, I've shown as the second option. It's no less "hacky" than the way I've shown it... the clearfix just takes steps to ensure that the content that gets added takes up no additional space within the div. The correct way to handle this is using theoverflow
property as shown above... unless you have a specific need to support a browser where you're sure that theoverflow
property won't work as designed. -
Lee over 13 years@Moshe: To be honest, I'm not sure which browsers would require the hack... I just remember that there was a point where we had to use the "clearing div" (or the clearfix, as @TehOne pointed out) -- but now all "up-level" browsers support the use of the
overflow
property in this situation. (you'd have to test IE6 to see which side of the line it falls on - I no longer support IE6, unless the client specifically requires it).