CSS float and Clear
Float —
Float property specifies how we can position an element within the container. Float is majorly used when we want to align elements horizontally next to each other.
- none
- left
- right
float: none;
This is the default property set on the element which means that the element will not float anywhere and will be there according to the normal document flow.
float:left;
This property will float (position) the element to the left side of the container, instead of
positioning the element with the default layout flow.
float:right;
This property will float (position) the element to the right side of the container, instead of positioning the element with the default layout flow.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img{
float: left;
border: 2px solid rgb(252, 4, 4);
}
.container{
border: 2px solid black;
background-color: antiquewhite;
/* display: flow-root; */
}
</style>
</head>
<body>
<div class="container">
<img src="/logo.jpg" width="250PX" alt="">
<div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas assumenda pariatur, aliquam architecto, iste dolore hic distinctio voluptas quia eius reprehenderit quae aspernatur a nemo blanditiis! Quod, possimus iure? Amet, vitae ab?
</p>
</div>
</div>
</body>
</html>
display: flow-root;
/*this will give to container so that image will not overflow */
Clear —
We can give clear property to an element when we want that no other element should be floated on its right side or left side .
we can set these clears —
- clear: left;
- clear: Right;
- clear: both;
<style>
img{
float: left;
border: 2px solid rgb(252, 4, 4);
}
.container{
border: 2px solid black;
background-color: antiquewhite;
display: flow-root;
}
p{
clear: left;
}
</style>
- if we set clear: left; to para, then this para will not allow any element float to its left side
So this was all about float and clear we used this a lot before when we used to make newspaper type content, most of the time in blogs, this thing was needed that there will be an image on one side, content on the other side and the image is floating on the left sometimes floating on the right and the article is being written, but the modern layouts are not designed like this.
Now we use Flexbox, Grid etc to make modern layout. but we should also know about Float & Clear , sometimes interviewer ask about .