# Floating elements

  • The float property can be used to move an HTML element to the far left or to the far right of its parent element
  • float is primarily used to float text around pictures

TIP

For the best viewing results, open this CodePen in a separate window by clicking on EDIT ON CODEPEN
Float none

# Float right

  • In Codepen, edit the first image by adding some extra code:
    • Float #img1 to the right side of its parent element
    • Give the image some extra space by adding some margin at the left and bottom

 
 
 


#img1 {
    float: right;
    margin-left: 1rem;
    margin-bottom: 1rem;
}
1
2
3
4
5

Float right

# Float left

  • In CodePen, edit the second image by adding some extra code:
    • Float #img2 to the left side of its parent element
    • Give the image some extra space by adding some margin at the right and bottom

 
 
 


#img2 {
    float: left;
    margin-right: 1rem;
    margin-bottom: 1rem;
}
1
2
3
4
5

Float left

# Stop floating

# Clear float

  • Sometimes you want the floating to stop because it will break the layout
  • In the next example, we want the second paragraph below the first paragraph

Clear float

  • You can stop the floating by adding the clear: both property to the second paragraph
    (both means that there can't be a floating element on the left or on the right)
  • You probably need this more than once in a website, so it's best to make a special class for this
.clearfloat {
    clear: both;
}
1
2
3
  • Add the class .clearfloat to the second paragraph
 




<p class="clearfloat">
    <img ... />
    ...
</p>
1
2
3
4

Clear float

# Clear fix

  • Clearing floats is not always a good solution
  • Let's go back to the first example, but with some additional styling added to the paragraphs

Float - example with styling

  • If we add the class clearfloat to the second paragraph (as we did before), the floating stops, but the images don't stay within their parent paragraph

Float - example with styling - clearfloat

  • To fix this behavior (= to ensure that the parent element will expand to a proper height enclosing its floating children), you can use the style rule overflow: auto; on the parent (or ancestor) tag
  • You probably need this more than once in a website, so it's best to make a special class for this
.clearfix {
    overflow: auto;
}
1
2
3
  • Add the class clearfix to the p tag that contains the floating images (and remove the class clearfloat from the second paragraph)
 





<p class="clearfix">
    <img ... />
    <img ... />
    ...
</p>
1
2
3
4
5

Float - example with styling - clearfix

# Emmet

EMMET instruction result
fl + TAB float: left;
fl:r + TAB float: right;
cl + TAB clear: both;
cl:b + TAB clear: both;
ov:a + TAB overflow: auto;
Last Updated: 11/28/2020, 5:56:24 PM