Test your skills: Floats
The aim of this skill test is to assess whether you understand floats in CSS using the float
and clear
properties and values as well as other methods for clearing floats. You will be working through three small tasks that use different elements of the material you have just covered.
Note: Click "Play" in the code blocks below to edit the examples in the MDN Playground. You can also copy the code (click the clipboard icon) and paste it into an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels.
Task 1
In this task, you need to float the two elements with a class of float1
and float2
left and right, respectively. The text should then appear between the two boxes, as in the image below:
Try to update the code below to recreate the finished example:
<div class="box">
<div class="float float1">One</div>
<div class="float float2">Two</div>
<p>The two boxes should float to either side of this text.</p>
</div>
.float1 {
}
.float2 {
}
Click here to show the solution
You can use float
for both boxes:
.float1 {
float: left;
}
.float2 {
float: right;
}
Task 2
In this task, the element with a class of float
should be floated left. Then we want the first line of text to display next to that element, but the following line of text (which has a class of below
) to display underneath it.
Your final result should look like the image below:
Try to update the code below to recreate the finished example:
<div class="box">
<div class="float">Float</div>
<p>This sentence appears next to the float.</p>
<p class="below">Make this sentence appear below the float.</p>
</div>
.float {
}
.below {
}
Click here to show the solution
You need to flow the item left, then add clear: left
to the class for the second paragraph:
.float {
float: left;
}
.below {
clear: left;
}
Task 3
In this task, we have a floated element. The box wrapping the float and text is displaying behind the float. Use the most up-to-date method available to cause the box background to extend to below the float, as in the image below:
Try to update the code below to recreate the finished example:
<div class="box">
<div class="float">Float</div>
<p>This sentence appears next to the float.</p>
</div>
.float {
float: right;
}
.box {
}
Click here to show the solution
Clear the box underneath the floated item by adding display: flow-root
to the class for .box
.
Other methods might be to use overflow
or a clearfix hack, however the learning materials detail the flow-root
method as the modern way to achieve this.
.box {
display: flow-root;
}