CSS clear is a property used to control the behavior of elements concerning floated elements within the same containing element. When an element is floated, it is taken out of the normal document flow, which can affect the layout of subsequent elements. The clear property allows you to specify whether an element should be moved below any floated elements that precede it or not.

There are four possible values for the clear property:

  1. clear: left;: The element will not be allowed to float on the left side of any preceding floated elements.

  2. clear: right;: The element will not be allowed to float on the right side of any preceding floated elements.

  3. clear: both;: The element will not be allowed to float on either the left or right side of any preceding floated elements. It will be moved below any floated elements.

  4. clear: none; (default): The element will be allowed to float on either side of any preceding floated elements.

Here are some examples to illustrate the usage of the clear property:

1. Clearing floats to the left:

HTML:

<div class="container">
  <div class="box float-left">Float Left</div>
  <div class="box clear-left">Clear Left</div>
</div>

 

CSS:

.container {
  width: 300px;
}

.box {
  width: 100px;
  height: 100px;
  margin: 5px;
}

.float-left {
  float: left;
}

.clear-left {
  clear: left;
}

2. Clearing floats to the right:

HTML:

<div class="container">
  <div class="box float-right">Float Right</div>
  <div class="box clear-right">Clear Right</div>
</div>

 

CSS:

.container {
  width: 300px;
}

.box {
  width: 100px;
  height: 100px;
  margin: 5px;
}

.float-right {
  float: right;
}

.clear-right {
  clear: right;
}

3. Clearing floats on both sides:

HTML:

<div class="container">
  <div class="box float-left">Float Left</div>
  <div class="box float-right">Float Right</div>
  <div class="box clear-both">Clear Both</div>
</div>

 

CSS:

.container {
  width: 300px;
}

.box {
  width: 100px;
  height: 100px;
  margin: 5px;
}

.float-left {
  float: left;
}

.float-right {
  float: right;
}

.clear-both {
  clear: both;
}

4. Using clear within a multi-column layout:

HTML:

<div class="column">
  <p>Column 1</p>
</div>
<div class="column">
  <p>Column 2</p>
</div>
<div class="clearfix"></div>

 

CSS:

.column {
  width: 150px;
  float: left;
}

.clearfix {
  clear: both;
}

In this example, we use the clearfix class to clear the floats after the two columns to ensure that subsequent content is not affected by the floated elements.

Latest Tutorial

Newly published tutorials

How to Make an AWS S3 Bucket Public

Learn how we can make an AWS S3 bucket public

Laravel 10 - Send mail using AWS SES

Learn to send Email using Laravel 10 with AWS SES service.

Laravel 10 - Tutorial on how to use jQuery to validate the form

Learn how to use jQuery in Laravel 10 to validate the form