# 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 right
- In Codepen, edit the first image by adding some extra code:
- Float
#img1
to theright
side of its parent element - Give the image some extra space by adding some margin at the
left
andbottom
- Float
#img1 {
float: right;
margin-left: 1rem;
margin-bottom: 1rem;
}
1
2
3
4
5
2
3
4
5
# Float left
- In CodePen, edit the second image by adding some extra code:
- Float
#img2
to theleft
side of its parent element - Give the image some extra space by adding some margin at the
right
andbottom
- Float
#img2 {
float: left;
margin-right: 1rem;
margin-bottom: 1rem;
}
1
2
3
4
5
2
3
4
5
# 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
- 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
2
3
- Add the class
.clearfloat
to the second paragraph
<p class="clearfloat">
<img ... />
...
</p>
1
2
3
4
2
3
4
# 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
- 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
- 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
2
3
- Add the class
clearfix
to thep
tag that contains the floating images (and remove the classclearfloat
from the second paragraph)
<p class="clearfix">
<img ... />
<img ... />
...
</p>
1
2
3
4
5
2
3
4
5
# 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; |