- Get link
- X
- Other Apps
In CSS, clear and clearfix are related to the float property. They help control how elements behave when other element are floated.
1.CSS CLEAR PROPERTY
The clear property prevents an element from sitting next to floated elements. It moves the element below the specified floats.
Syntax
clear: none | left | right | both;none— Default; allows floating elements on either side.left— Moves the element below left-floated elements.right— Moves the element below right-floated elements.both— Moves the element below floats on both sides.
Example
<div class="box">Floated box</div>
<p class="next">Next paragraph</p>.box {
float: left;
width: 120px;
height: 80px;
background: lightblue;
}
.next {
clear: both;
}Result: The paragraph starts below the floated box instead of wrapping beside it.
2. CSS clearfix hack
The clearfix hack is a technique used to make a parent element contain its floated children.
The problem
When a child element uses float, the parent may collapse to a height of zero if it contains no other in-flow content.
<div class="container">
<div class="box">Floated child</div>
</div>.container {
background: lightgray;
}
.box {
float: left;
width: 150px;
height: 100px;
background: lightblue;
}The parent background might not extend around the floated child because the float is removed from normal document flow.
Solution: clearfix hack
.clearfix::after {
content: "";
display: table;
clear: both;
}Apply it to the parent:
<div class="container clearfix">
<div class="box">Floated child</div>
</div>Now the parent expands to contain the floated child.
3. clear vs. clearfix
Feature |
| Clearfix hack |
|---|---|---|
Purpose | Moves an element below floats | Makes a parent contain floated children |
Applied to | An element after or around floats | The parent containing floats |
Uses |
|
|
Main effect | Controls element placement | Fixes parent height and background |
4. Modern alternative to clearfix
Today, you can often avoid the clearfix hack by using Flexbox, Grid, or display: flow-root.
.container {
display: flow-root;
}display: flow-root creates a block formatting context, allowing the parent to contain its floated children without an extra pseudo-element.
Remember:
clear= move an element below floats.clearfix= make the parent contain floated children.display: flow-root= a modern alternative to clearfix.
.png)
Comments
Post a Comment