Using the float
Property
The float
property allows an element to be taken out of the normal document flow and be positioned to the left or right of its container. Common values for float
include left
, right
, and none
(default).
In this example, .image-left
will float to the left, and .image-right
will float to the right. The margin
is added to create spacing between the floated element and surrounding content.
.image-left { float: left; margin: 10px; } .image-right { float: right; margin: 10px; }
Clearing Floats
When elements are floated, the following content can wrap around them. The clear
property is used to prevent this, ensuring that the next element moves below the floated elements.
.clear { clear: both; /* can also use left or right to clear specific sides */ }
CSS Floats Example Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Float Example</title> <style> .container { width: 600px; margin: auto; } .image-left { float: left; width: 150px; margin-right: 10px; /* Adds space to the right of the image */ } .clear { clear: both; } </style> </head> <body> <div class="container"> <img src="path-to-your-image.jpg" alt="Example Image Left" class="image-left"> <p>Text content that will wrap around the left floated image. Text content that will wrap around the left floated image. Text content that will wrap around the left floated image. Text content that will wrap around the left floated image. Text content that will wrap around the left floated image.</p> <p class="clear">This paragraph will clear the float and move below the image.</p> </div> </body> </html>