CSS Float
The CSS float property is used to position an element to the left or right within its parent container, allowing text and inline elements to wrap around it. It is commonly used for images, sidebars, and content layout.
Syntax:
Syntax:
selector { float: value;}
Float Property Values
Value | Description |
---|---|
none | (Default) The element is not floated. |
left | Floats the element to the left of its container. |
right | Floats the element to the right of its container. |
initial | Sets to the default value (none). |
inherit | Inherits the float value from the parent element. |
clear Property
When elements float, following content can wrap around them. The clear property is used to prevent content from flowing around floated elements.
Value | Description |
---|---|
left | Prevents floating content to the left of the element. |
right | Prevents floating content to the right of the element. |
both | Prevents content from floating on both sides. |
none | Default. Allows floating content to appear. |
Example: Float Right
<!DOCTYPE html><html>
<head> <style> img { float: right; margin-left: 10px; } </style></head>
<body> <p> The following paragraph contains an image with the style <b>float: right</b>. The result is that the image will float to the right of the paragraph, and the text will wrap around it. </p>
<img src="good-morning.jpg" alt="Good Morning Friends" width="150" height="150" />
<p> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. </p></body>
</html>
Output:
.webp)
Use Cases
- Wrapping text around images.
- Creating responsive layouts without using flexbox or grid.
- Building sidebars or callouts.
Common Float Issues & Solutions
- Floated elements are removed from normal flow, which can cause parent containers to collapse.
- Use the clearfix technique to prevent layout issues:
.clearfix::after { content: ""; display: table; clear: both;}
Apply .clearfix to the parent of floated elements.