As you can see in the image above ( image source), floats are a basic tool in web design that allows you to position an element to the left or right of its container. For example, you can use floats to position an image to the left of a paragraph of text. The code (HTML and CSS) for an image floated to the left of a paragraph would look something like this:
<style>
img {
float: left;
width: 200px;
height: 200px;
}
</style>
<img src="...">
<p>Lorem ipsum dolor sit amet...</p>
As you can see, the float
property is used to float the image to the left. The width
and height
properties are used to set the size of the image. The float
property can have one of the following values:
left
: This value floats the element to the left.right
: This value floats the element to the right.none
: This value does not float the element. This is the default value.
The Clear Property#
The clear property is used to specify which side of an element should not be adjacent to a floating element. This property is useful when you want to ensure that a specific element is below all the floated elements.
There are several values that you can use with the clear property:
none
: This is the default value and allows the element to be adjacent to any floated element.left
: This value specifies that the element should not be adjacent to any floated element on the left side.right
: This value specifies that the element should not be adjacent to any floated element on the right side.both
: This value specifies that the element should not be adjacent to any floated element on either side.
Here’s an example:
.clearfix {
clear: both;
}
<div class="clearfix">
<img src="https://www.w3schools.com/css/img_fjords.jpg" alt="Fjords" width="300" height="200">
<p>Lorem ipsum dolor sit amet...</p>
</div>
In this code, we have set the clear property to both for the .clearfix
class, which ensures that the element with this class is below any floated elements on both the left and right sides. In other words, the element with this class will not be on the same line as any floated elements.
Conclusion#
In this article, we have explored the float and clear properties in CSS. We have seen how to use these properties to create a simple layout with a floating image and text. We have also seen how to use the clear property to ensure that an element is below any floated elements.