How to Write Defensive CSS: Prevent Scroll Chaining, Variable Fallbacks, and Layout Breakage
This article presents practical defensive CSS techniques—including using overscroll-behavior to stop scroll chaining, var() fallbacks for custom properties, min‑width/min‑height instead of fixed dimensions, proper background-repeat handling, and vertical media queries—to create more robust, responsive web layouts.
Usually we want methods to avoid unexpected CSS issues; because web content can change dynamically, CSS problems become more likely. This article introduces a series of defensive CSS code snippets to help write more robust CSS and reduce style problems caused by dynamic content changes.
Cancel Scroll Chaining
When a modal is opened and scrolled to the bottom, further scrolling can cause the underlying body element to scroll, a phenomenon known as scroll chaining.
Previously this required hacks, but now the CSS
overscroll-behaviorproperty can be used to contain scrolling.
<code>.modal__content {
overscroll-behavior-y: contain;
overflow-y: auto;
}
</code>Custom Property Fallback Values
CSS custom properties (variables) are increasingly used in web design, but their values may become invalid, especially when set via JavaScript.
If a variable is undefined, properties like
max-widthcan compute to
none. Using
var()with a fallback value prevents this.
<code>.message__bubble {
max-width: calc(100% - var(--actions-width, 70px));
}
</code>Use Flexible Width and Height
Fixed Height
Fixed height can cause layout breakage when content exceeds the set height. Use
min-heightinstead of
heightto allow growth.
<code>.hero {
min-height: 350px;
}
</code>Fixed Width
Fixed width on buttons can cause text to overflow and create a poor user experience. Replace
widthwith
min-widthto allow the button to expand as needed.
<code>.button {
min-width: 100px;
}
</code>Don’t Forget background-repeat
When using large images as backgrounds, they may repeat on large screens. Setting
background-repeat: no-repeatprevents this.
<code>.hero {
background-image: url('..');
background-repeat: no-repeat;
}
</code>Vertical Media Queries
Testing component layout by adjusting browser height can reveal issues such as overlapping navigation in a sidebar. Using a height‑based media query ensures the sticky secondary navigation only activates on tall viewports, avoiding overlap.
<code>@media (min-height: 600px) {
.aside__secondary {
position: sticky;
bottom: 0;
}
}
</code>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.