Most of the clearfix techniques out there involves adding things at the very bottom of the parent container, and I prefer the pseudo element approach the most since it doesn't add unneeded elements into the HTML.
However, recently I found that I am dealing with a container that has some children floating but not all. Say the first 2 children the first floats left and the second floats right. I need a way to clear the float right after the second element, so the content below doesn't get squeezed in between them. Is there a way to clear floating elements in the middle but without adding clearfix element?
Below is an example:
HTML
<div class="container">
<div class="child">
first child!
</div>
<div class="child">
second child!
</div>
<div class="child">
third child!
</div>
</div>
CSS
.container {
width: 200px;
}
.child:nth-child(1) {
float: left;
background: yellow;
}
.child:nth-child(2) {
float: right;
background: red;
}
.child:nth-child(3) {
background: blue;
color: white;
}
Please see this jsfiddle to see what I have right now.
To clear a float, add the clear property to the element that needs to clear the float. This is usually the element after the floated element. The clear property can take the values of left , right , and both . Usually you'll want to use both.
The clear property is used to specify that which side of floating elements are not allowed to float. It sets or returns the position of the element in relation to floating the objects. The “clear: both” means floating the elements are not allowed to float on both sides.
The clear CSS property sets whether an element must be moved below (cleared) floating elements that precede it. The clear property applies to floating and non-floating elements.
The clearfix, for those unaware, is a CSS hack that solves a persistent bug that occurs when two floated elements are stacked next to each other. When elements are aligned this way, the parent container ends up with a height of 0, and it can easily wreak havoc on a layout.
Just use clear: both;
on the 3rd element, this way you don't have to use <div style="clear: both;"></div>
after the floated elements.
.child:nth-child(3) {
background: blue;
color: white;
clear: both;
}
Demo
Also, if whenever you are looking to clear a parent element without adding an extra element or using overflow: hidden;
which is a dirty way to clear
floats, you can call a class
on the parent element, with the properties below
.clear:after {
content: "";
display: table;
clear: both;
}
For example
<div class="wrapper clear">
<div class="left_floated_div"></div>
<div class="right_floated_div"></div>
</div>
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