How to Write Defensive CSS: Prevent Layout Issues with Flex, Grid, and Overflow
This article presents practical defensive CSS techniques—including handling justify-content space-between, image text fallbacks, fixed grid values, overflow control, and scrollbar gutter—to create robust, responsive layouts that gracefully adapt to dynamic content changes.
This article, translated from Ahmad Shadeed’s “Defensive CSS”, presents a collection of defensive CSS code snippets to help write more robust CSS and avoid unexpected style issues caused by dynamic content.
Using justify-content: space-between
In a flex container,
justify-contentcan separate child elements, but when the number of children changes the layout may look odd. The spacing is generated by
justify-content: space-between, not by
gapor
margin. When fewer than four items are present, the effect can be unfriendly. Solutions include using
margin, the
gapproperty (browser support permitting),
padding, or adding an empty placeholder element.
Example using
gap:
<code>.wrapper {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
</code>Text on images
When displaying text over an image, consider the appearance if the image fails to load. If the image is missing, white text on a white background becomes unreadable. Adding a background color to the
<img>element solves this, applied only when the image fails.
<code>.card__img {
background-color: grey;
}
</code>Watch out for fixed values in CSS Grid
When a grid container defines fixed column widths, small viewports may lack space, causing layout issues. Use media queries to adjust the grid for smaller screens.
<code>.wrapper {
display: grid;
grid-template-columns: 250px 1fr;
gap: 1rem;
}
@media (min-width: 600px) {
.wrapper {
display: grid;
grid-template-columns: 250px 1fr;
gap: 1rem;
}
}
</code>Show scrollbars only when necessary
For long content, set
overflowto
auto(or
overflow-y: auto) so scrollbars appear only when needed. Avoid forcing
overflow: scrollon short content.
<code>.element {
overflow-y: auto;
}
</code>Prevent layout shift from scrollbar gutter
Scrollbars occupy space, shrinking the content area. Use
scrollbar-gutter: stableto reserve space and avoid layout changes when a scrollbar appears.
<code>.element {
scrollbar-gutter: stable;
}
</code>This is the third part of the series; previous parts can be read via the provided links.
KooFE Frontend Team
Follow the latest frontend updates
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.