Ready for a bit of an adventure? In my humble opinion, coming across this scenario in real-world practice is highly unlikely. Personally, I have yet to find a practical use for it.
The concept we're diving into is clearance, which occurs when a box is moved down to clear a float within its block formatting context.
This is achieved using clear:left
or clear:right
or clear:both
. If the box would otherwise be next to a float on the side that it's cleared, it will be shifted down until its border-box is completely below the margin box of the float.
Let's explore an example:
body {
border: 1px solid red;
}
main {
padding-top:1px;
margin-bottom:100px;
}
aside {
background-color: tan;
height: 100px;
width: 200px;
float: left;
}
header {
margin-top:90px;
}
footer {
margin-bottom:100px;
}
<body>
<main>
<aside>The aside</aside>
<header></header>
<footer></footer>
</main>
</body>
In this setup, the aside element acts as the float. The top padding on the main element ensures no collapsing can happen with the top margins of the main or body elements.
Due to the empty content of the header and footer elements, along with the margins set, they collapse together, resulting in a total vertical margin of 100px. The body element contains them within its content box, making its height 101px (1px padding + 100px margin).
Now, let's introduce clear:left
to the header element.
body {
border: 1px solid red;
}
main {
padding-top:1px;
margin-bottom:100px;
}
aside {
background-color: tan;
height: 100px;
width: 200px;
float: left;
}
header {
margin-top:90px;
clear:left;
}
footer {
margin-bottom:100px;
}
<body>
<main>
<aside>The aside</aside>
<header></header>
<footer></footer>
</main>
</body>
After this change, the body element's height increases to 211px!.
By assigning clearance to the header element, its content shifts down by 10px to clear the float. This adjustment triggers further movement due to margin interactions, altering the overall layout.
This leads us to a key observation - the impact of having an element with clearance on margin collapse behavior.
Exploring different scenarios helps solidify our understanding of how clearances and margins influence layout outcomes.