The float
property specifies whether an element should float to the left, right, or not at all.
Ex: Say you have a tweet with an avatar on the left, and text on the right:
<body>
<article class="tweet">
<!-- Image -->
<div class="avatar"></div>
<p>
<!-- tweet Text... -->
</p>
<p class="clear">
<!-- comment, like, share Text... -->
</p>
</article>
</body>
.avatar {
width: 5rem;
height: 5rem;
background-color: gold;
/* set the avator float to the left */
float: left;
/* set a margin between image and text */
margin-right: 1rem;
}
Note: Elements next to a floating element will flow around it. To avoid this, use the clear
property.
.clear {
clear: both;
}
Another problem is when we have short text (shorter than avator) inside the .tweet
class, the border will not include the avator, to avoid this, we need to clear
again at the end of parent class, i.e. .tweet
We can either add another <div class="clear">
at the end:
<body>
<div class="avatar"></div>
<!-- ... -->
<div class="clear"></div>
</body>
Or add pseudo element ::after
in css:
/* replace '.tweet' with '.clearfix' and include multiple cases */
.tweet::after {
content: "";
display: block;
clear: both;
}