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
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>
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>
Add overflow: hidden;
to #wrap. This is a clear fix
. Here's some documentation about it: http://positioniseverything.net/easyclearing.html
LE: There are also multiple ways you can achieve this, depending of the browser compatibilty:
#wrap { overflow: hidden; }
clear: both
.#wrap:after { clear: both; content: ""; display: table;}
<div style="clear:both"></div>
I preffer not
to use the 3rd one as you get extra HTML markup.
Try adding overflow: hidden
to your #wrap
div
.
I've come to start using this "micro-clearfix" solution from Nicolas Gallagher.
http://nicolasgallagher.com/micro-clearfix-hack/
/* For modern browsers */
.cf:before,
.cf:after {
content:"";
display:table;
}
.cf:after {
clear:both;
}
/* For IE 6/7 (trigger hasLayout) */
.cf {
*zoom:1;
}
Just add that to your CSS and any floated element, add the "cf" class to the wrapper of any any element that has floated children.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With