Categories
Web development

CSS float Property

CSS float Property

The CSS float property defines whether an element should float to the left, or right (or not at all).

Demo:

Syntax:

float: none|left|right;

none (default) – the element will be displayed just where it occurs in the text.

left – the element floats to the left of its container.

right – the element floats to the right of its container.

Note: Elements next to a floating element will flow around it. To avoid this, use the clear property.

Example1:

Let an image float to the right:

<!DOCTYPE html>
<html>
<head>
<style>
img {
  float: right;
}
</style>
</head>
<body>

<p><img src="https://i0.wp.com/lenadesign.org/wp-content/uploads/2021/10/css-clock-animation.jpg?ssl=1&resize=320%2C320" width="auto" height="120";>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. </p>

</body>
</html>

Output:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio.

Example2:

Don’t allow floating elements on the left or the right side of a defined <p> element:

<!DOCTYPE html>
<html>
<head>
<style>
img {
  float: left;
}

#clearOne {
  clear: left;
}
</style>
</head>
<body>

<div class="ex-1">
    <h4>with clear:</h4>
<img src="https://i0.wp.com/lenadesign.org/wp-content/uploads/2021/10/css-clock-animation.jpg?ssl=1&resize=320%2C320" width="auto" height="120";>
    
<div id="clearOne" style="font-size: 25px;">This is some text.<br>This is some text.<br>This is some text.<br>This is some text.</div>
    </div>
    <br>
    <div class="ex-2">
    <h4>without clear:</h4>
<img src="https://i0.wp.com/lenadesign.org/wp-content/uploads/2021/10/css-clock-animation.jpg?ssl=1&resize=320%2C320" width="auto" height="120";>
    
<div id="clearTwo" style="font-size: 25px;">This is some text.<br>This is some text.<br>This is some text.<br>This is some text.</div>
    </div>

</body>
</html>

Output:

with clear:

This is some text.
This is some text.
This is some text.
This is some text.

without clear:

This is some text.
This is some text.
This is some text.
This is some text.

Enjoy coding!

Read also:

CSS text-align Property

CSS clear Property

CSS Float Tutorial