Float
- Used for positioning and specifies how an element should float.
- Possible values are
left
,right
,none
None (default)
<div>
<img src="images/sky.jpg" alt="sky"><p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nihil, molestiae?</p>
</div>
Left
Float the element to the left
Example 1
img {
float: left;
}
Example 2
<nav>
<div style="background-color:red"></div>
<div style="background-color:green"></div>
<div style="background-color:blue"></div>
</nav>
Right
Float the element to the right
img {
float: right;
}
Clear
- Specifies what should happen with the element that is next to a floating element.
- Possible values
none
- The element is not pushed below left or right floated elements. This is defaultleft
- The element is pushed below left floated elementsright
- The element is pushed below right floated elementsboth
- The element is pushed below both left and right floated elements
<div>
<img src="images/sky.jpg" alt="sky"><p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nihil, molestiae?<p>
<p style="clear:both">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nihil, molestiae?<p>
</div>
Collapsing
- Parent elements don't see floated elements, and they collapse.
- To fix this add a block element or an after pseudo-element and clear the float
#div1 {
border: 2px solid blue;
}
img {
float: left
}
<div id="div1">
<img src="images/sky.jpg" alt="sky">
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rem nostrum in illo eius quaerat soluta rerum, id expedita unde, labore quisquam dignissimos magni ipsum at nam vero sit? Provident sequi placeat sed vitae itaque culpa temporibus iste quo veritatis nobis at, exercitationem perspiciatis? Inventore vel eveniet, nostrum est laboriosam totam?</p>
</div>
Option 1
.clearfix {
clear: both
}
Option 2
::after {
content: '';
display: block;
clear: both
}