<h2>Collapsed floats</h2>
<div>
<span>You</span>
<span>can't</span>
<span>see</span>
<span>any</span>
<span>red!</span>
</div>
<p>The div element has collapsed. Background color cannot be seen.</p>
<hr />
<h2>Contain layout</h2>
<div class="contain-layout">
<span>You</span>
<span>can</span>
<span>see</span>
<span>red!</span>
</div>
<p><code>contain: layout;</code> will include floats.</p>
<hr />
<h2>Grid container</h2>
<div class="grid">
<div>
<span>You</span>
<span>can</span>
<span>see</span>
<span>red!</span>
</div>
</div>
<p>Having <code>display: grid;</code> on an extra containing element will cause the grid child element to also contain floats. Flexbox would also work, but flex by default would also shrink the width of the element.</p>
<hr />
<h2>Inline-block</h2>
<div class="inline-block">
<span>You</span>
<span>can</span>
<span>see</span>
<span>red!</span>
</div>
<p>Inline blocks will contain floats. It is the most backwards compatible solution which does not involve using the traditionally more common clearfix hack.</p>
span {
float: left;
padding: 0.125rem;
}
div {
background: red;
font-weight: bold;
}
div[class] {
color: white;
}
/* least code solution, wide support since March 2022 */
.contain-layout {
contain: layout;
}
/* extra wrapper solution, wide support since October 2017 */
.grid {
display: grid;
/* Proves that the background color is from the child and not this element. */
background: unset;
}
/* backwards compatible solution, wide support since March 2009 (IE8) */
.inline-block {
display: inline-block;
/* Pretend block element behavior. */
width: 100%;
/* Remove white space caused by baseline. */
vertical-align: middle;
/* Required when adding padding or borders. */
box-sizing: border-box;
}
/* minimal styles to make things prettier */
body {
/* https://modernfontstacks.com/ */
--classical-humanist: Optima, Candara, "Noto Sans", source-sans-pro,
sans-serif;
font-family: var(--classical-humanist);
font-size: 1.125rem;
margin: auto;
max-width: 30rem;
padding: 1rem;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.