Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Align elements using the CSS float property
The CSS float property is used to align elements to the left or right side of their container, allowing other content to wrap around them. This property was traditionally used for creating layouts before modern techniques like flexbox and grid.
Syntax
selector {
float: value;
}
Possible Values
| Value | Description |
|---|---|
left |
Element floats to the left side |
right |
Element floats to the right side |
none |
Element does not float (default) |
Example: Right Float Alignment
The following example demonstrates how to align an element to the right using the float property −
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
float: right;
width: 200px;
border: 1px dashed blue;
padding: 5px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<h1>Heading</h1>
<div class="demo">
<p>This is demo text and right aligned.</p>
</div>
<p>This text will wrap around the floated element on the left side.</p>
</body>
</html>
A heading appears at the top, followed by a gray box with dashed blue border floating to the right containing "This is demo text and right aligned." The paragraph text wraps around the floated box on the left side.
Example: Left Float Alignment
Here's an example showing how to float an element to the left −
<!DOCTYPE html>
<html>
<head>
<style>
.left-box {
float: left;
width: 150px;
height: 100px;
background-color: #4CAF50;
color: white;
text-align: center;
line-height: 100px;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="left-box">Floated Left</div>
<p>This paragraph text flows around the green box that is floated to the left. The text automatically wraps to the right side of the floated element.</p>
</body>
</html>
A green box with white text "Floated Left" appears on the left side, with paragraph text flowing around it on the right side.
Conclusion
The float property effectively aligns elements to the left or right while allowing content to wrap around them. While still useful for specific cases, modern layout methods like flexbox and grid are now preferred for complex layouts.
Advertisements
