Creating a Web Layout Using Float
This tutorial explains how to create a simple 3-column web layout using the CSS float
property.
HTML Structure with Internal CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web layout</title>
</head>
<body>
<style>
.main{
background-color: blueviolet;
}
.main::after{
content: "";
clear: both;
display: table;
}
.box1,
.box2,
.box3 {
background-color: aqua;
width: calc(33.33% - 60px);
float: left;
margin: 15px;
padding: 15px;
}
</style>
<div class="main">
<div class="box1">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam, esse
assumenda! Modi deserunt eligendi voluptatibus explicabo pariatur.
Culpa harum quo ea alias quos magnam excepturi, quis porro, quidem
officia quam!
</p>
</div>
<div class="box2">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque quis
sed iure incidunt nesciunt adipisci aliquid asperiores, rerum, amet at
dolor laborum magnam aut voluptatibus facere voluptatem pariatur
eligendi obcaecati!
</p>
</div>
<div class="box3">
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum soluta
cupiditate ratione quod dolores cumque perspiciatis asperiores!
Maiores accusamus dolore corporis rem totam, velit unde,
exercitationem, qui impedit ipsam sed?
</p>
</div>
</div>
</body>
</html>
Run Code
Explanation
1. The Wrapper Container
The outer container .main
is styled with a background color and a clearfix to ensure the floated child elements are contained within it. This is achieved using the ::after
pseudo-element with content: "";
, clear: both;
, and display: table;
.
2. Floated Child Elements
The child elements .box1
, .box2
, and .box3
are floated to the left using float: left;
. Each box is given a calculated width using calc(33.33% - 60px)
to ensure three boxes fit in one row while accounting for margins and padding.
3. Styling Boxes
Each box has a background color, margin, and padding to provide spacing and visual separation.
Benefits of Using Float
- Simple to implement for multi-column layouts.
- Provides control over individual element positioning.
Drawbacks of Float
- Requires clearfix to manage floated elements.
- Can be challenging to use for more complex layouts compared to Flexbox or Grid.
Floats are a traditional way of creating layouts, but for modern responsive designs, consider using Flexbox or Grid Layout for better flexibility and ease of use.