CSS for Web Development

0% completed

Previous
Next
Clearing floats

When elements are floated, subsequent content might wrap around them in unexpected ways. To prevent this, you clear the floats. Clearing floats makes sure that an element appears below the floated elements. This is often necessary to maintain the intended layout and prevent overlapping or misalignment of content.

Syntax

Follow the code block below to clear floats in CSS:

/* Clear floats using the clear property */ clear: none | left | right | both;

Explanation:

  • clear: left;
    • Prevents the element from sitting next to left-floated elements.
  • clear: right;
    • Prevents the element from sitting next to right-floated elements.
  • clear: both;
    • The element will move below any floated elements on either side.

Example 1: Clearing Floats with clear: both;

In this example, we float an image to the left of some text. A subsequent <div> clears the float so that it starts on a new line below the floated elements.

HTML

. . . .

Explanation:

  • Float Property:
    • The image is floated to the left using .float-left.
  • Clear Property:
    • The .clearfix class with clear: both; forces subsequent content to start below the floated elements.
  • Outcome:
    • The first paragraph wraps next to the image, while the second paragraph begins on a new line due to clearing.

Example 2: Clearing Specific Sides

In this example, we float two boxes: one to the left and one to the right. A <div> that clears the left float is used to ensure the following content does not wrap around the left-floated element.

HTML

. . . .

Explanation:

  • Floated Elements:
    • One box is floated to the left, another to the right.
  • Clear Property:
    • The .clear-left class using clear: left; clears the left float.
  • Outcome:
    • The paragraph starts on a new line below the floated boxes, ensuring proper layout without overlapping.

This lesson shows how to clear floats using the clear property in CSS. By applying clear: both; or clear: left/right;, you can control the flow of your layout and maintain a clean, organized design.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next