Debugging CSS and Best Practices: A Troubleshooting Guide
A systematic way to find out why CSS doesn't do what you expect: five questions to ask, a symptom-by-symptom guide to common bugs and fixes, debug stylesheets, finding overflow, isolating problems, and practices that prevent bugs.
kvi5hnuCode Sprout team member11 min readOn this page
Most CSS bugs aren't mysteries. They come from a small set of causes: a rule that doesn't match, one that loses in the cascade, a value the browser rejected, a property that doesn't apply in that layout context, or a box behaving according to rules you didn't expect. This article turns that into a routine you can follow, then lists common symptoms with their usual causes. Article 4 covers the DevTools panels used along the way.
Five questions, in order
When a style doesn't show up, select the element in DevTools and work through these questions. Each one rules out a whole class of causes.
- Does the rule match the element? If the rule doesn't appear in the Styles pane, the selector doesn't match: a typo, a missing class, a wrong combinator, the element being in a shadow tree (article 14), or a media, container or
@supportscondition that's false. Test the selector in the console withdocument.querySelectorAll('…'). - Does the declaration win? A struck-through declaration lost in the cascade. The Computed pane shows the winner and its source. Check layers before specificity (article 20), then specificity (article 15), then order. Remember that unlayered styles beat all layers, and
!importantreverses layer order. - Is the value valid? A declaration with a warning icon was rejected while parsing, typically for a typo, a missing unit or an unsupported value. A custom property can also make a declaration invalid at computed-value time (article 27): it looks valid in the source but computes to the inherited or initial value.
- Does the property apply here? Some properties only work in certain contexts:
flex-growdoes nothing unless the element is a flex item,z-indexneeds a positioned element or a flex or grid item,widthdoesn't affect inline elements, andgapneeds flex, grid or multi-column. Chrome and Firefox mark such declarations as inactive and explain why. - Is the layout doing something you didn't expect? The value computed fine, but the box isn't where you think: margins collapsed, a percentage resolved against a different box, a containing block or stacking context changed, or an item was sized by its content. The box-model view and the flex and grid overlays help here, and the next section lists the usual suspects.
Common symptoms

| Symptom | Usual cause | Fix | Article |
|---|---|---|---|
| A rule has no effect at all | Selector doesn't match, or a condition is false | Check in Styles pane; test with querySelectorAll | 4 |
| A declaration is struck through | It lost in the cascade | Use a later layer, lower other specificity with :where() | 15, 20 |
z-index: 9999 is still behind | It's inside another stacking context | Find the ancestor creating it (opacity, transform, filter, isolation, positioned with z-index) | 58 |
height: 100% does nothing | The parent's height isn't definite | Give the parent a height, or use flex or grid stretching | 37 |
| A gap appears under an image | The image is inline, on the text baseline | display: block or vertical-align: middle | 45 |
| Vertical margins disappear or leak out of a parent | Margin collapsing | Use gap or padding, or make the parent a flow root (display: flow-root) | 40 |
position: sticky doesn't stick | An ancestor with overflow other than visible became its scroll container, or there's no inset like top | Remove the overflow, use overflow: clip, or set top | 57 |
position: absolute is placed relative to the wrong box | The nearest positioned ancestor isn't the one you meant; transform or filter also create containing blocks | Set position: relative on the intended ancestor | 56 |
position: fixed scrolls with the page | An ancestor has transform, filter, backdrop-filter, perspective, will-change: transform or contain: layout/paint | Move the element out, or remove that property | 57, 111 |
| Text or an item overflows a flex or grid container | min-width: auto keeps items as wide as their content | min-width: 0 (flex) or minmax(0, 1fr) (grid), plus overflow-wrap | 62, 66 |
| The page scrolls sideways on phones | Something is wider than the viewport: fixed widths, 100vw with a scrollbar, long words, negative margins | Find it with the outline trick below | 75 |
aspect-ratio is ignored | Both dimensions are set, or content forces a larger size | Set one dimension only; add min-height: 0 if content is taller | 38 |
| A transition doesn't run, or only runs one way | The property is discrete, the value is auto, or the element appears from display: none; one-way when transition is only on the :hover rule | Put transition on the base rule; see @starting-style and interpolate-size | 106, 108 |
| A custom property seems ignored | Misspelled name, defined on the wrong element, invalid at computed-value time | Inspect the computed value; give var() a fallback | 27 |
| A container query never matches | No ancestor has container-type, or the element queries itself | Put container-type on an ancestor | 78 |
| Fonts flash or swap | A web font loads late | font-display, preloading, fallback metrics | 84 |
| Layout is fine in Chrome but not in Safari or Firefox | Unsupported feature, or a different default | Check compatibility data; use @supports with a fallback | 6, 80 |
The figure above shows six of these, broken on the left and fixed on the right in each pair. In each case, the CSS was valid and the browser followed the rules exactly; the fix was knowing which rule applied.
Techniques
Outline everything
To see where boxes actually are, outline them. Outlines don't take up space, so they don't change the layout you're debugging, unlike borders:
* { outline: 1px solid rgb(255 0 0 / 0.5); }
* * { outline-color: rgb(0 128 0 / 0.5); }
* * * { outline-color: rgb(0 0 255 / 0.5); }
This is the fastest way to find the element that sticks out and causes horizontal scrolling. You can also ask the page directly in the console:
[...document.querySelectorAll('*')].filter(el => el.getBoundingClientRect().right > document.documentElement.clientWidth);
A debug stylesheet
A few selectors can flag common markup problems while you develop. Keep them in a file you load only in development:
img:not([alt]) { outline: 4px solid magenta; } /* image without alt text */
a:not([href]), a[href=""], a[href="#"] { outline: 3px dashed magenta; } /* link that goes nowhere */
button:empty:not([aria-label], [aria-labelledby]) { outline: 3px solid magenta; } /* button without a name */
:is(h1, h2, h3, h4, h5, h6):empty { outline: 3px solid magenta; } /* empty heading */
[style] { outline: 3px dotted orange; } /* inline styles */

Nothing on the left looks wrong, but the debug view finds five problems at once: the second image has no alt, the second card's heading is empty, the Sign in link has no href, the Vancouver card has an inline style, and its button has neither text nor a label. These are hints, not a replacement for an accessibility checker, but they catch mistakes early.
Isolate the problem
- Toggle declarations in the Styles pane to find which one matters.
- Bisect: comment out half the stylesheet, see if the bug remains, and repeat with the half that has it.
- Build a minimal reproduction: copy the element and its CSS into an empty page or a playground. If the bug disappears, something you left out causes it, and you can add things back until it returns. A small reproduction is also what you need to ask for help or report a browser bug.
- Check computed values from the console:
getComputedStyle($0).positionreads any property of the element selected in DevTools, andCSS.supports('display: grid-lanes')tells you whether a feature is supported.
Emulate conditions
The Rendering panel in Chrome, and similar settings in Firefox and Safari, emulate dark mode, reduced motion, forced colors and print, and device toolbars emulate viewport sizes and touch. Test those states deliberately; bugs often hide in the ones you don't use yourself.
Best practices that prevent bugs
Structure
- Organize CSS in layers: reset, base, layout, components, utilities (article 117).
- Write modules with one class each, and variants as modifier classes; never style by location (article 116).
- Keep specificity low and flat. Use
:where()for defaults that should be easy to override. - Avoid
!importantexcept in utilities or resets that must win, and document why.
Values
- Use design tokens instead of magic numbers (article 118).
- Use
remfor font sizes and most spacing, so user settings are respected; avoid fixed heights on anything containing text. - Prefer intrinsic layout: flexbox and grid with
minmax(),auto-fitand container queries instead of many breakpoints. - Use logical properties (
margin-inline,padding-block) so layouts work in other writing directions (article 47).
Robustness
- Design for content that changes: long words, missing images, translated text two-thirds longer, empty states.
- Provide fallbacks with
@supportsfor features not in every browser you support, and test without them. - Respect user preferences:
prefers-reduced-motion,prefers-color-scheme, forced colors, and zoom up to 400%. - Keep focus visible: never remove
outlinewithout a:focus-visiblereplacement.
Process
- Document modules in a pattern library, and add screenshot tests for important ones (article 119).
- Lint with Stylelint, and format consistently.
- Test in Chrome, Firefox and Safari, including a phone; check compatibility data before using new features.
body { font: 0.85rem system-ui, sans-serif; margin: 0; }
.page { padding: 0.8rem; }
.bar { display: flex; justify-content: space-between; align-items: center; }
.bar a { margin-inline-start: 0.5rem; }
.hero { padding: 0.8rem; border-radius: 8px; background: #f4efe6; margin-block: 0.6rem; }
.hero h2 { margin: 0; }
.hero p { margin: 0.2rem 0 0; }
/* the bug: a fixed width wider than a phone screen */
.promo { width: 340px; padding: 0.6rem; background: #8a3b12; color: white; border-radius: 6px; }
.debug * { outline: 1px solid rgb(255 0 0 / 0.5); }
.debug .culprit { outline: 3px solid magenta; outline-offset: -3px; }
.tool { display: block; padding: 0.6rem 0.8rem 0; }
#report { margin: 0 0.8rem; color: #555; }
Turn on the outlines: the promo strip, with its fixed 340px width plus padding, sticks out of the 350px preview once the page padding is added, and the script names it. Change its width to max-width: 340px and run the check again.
What's current
- Chrome and Firefox DevTools flag inactive declarations and explain why; all three engines show layers, container queries, and flex and grid overlays.
- Chrome's Elements panel shows badges for scroll containers, containers, flex and grid; its Rendering panel emulates media features including forced colors and reduced transparency.
Common questions
My CSS works locally but not in production. Why? A different file order after bundling, a cached old stylesheet, or a build step that rewrote or removed rules. Compare the CSS actually served.
Why does DevTools show my rule but the element looks unchanged?
Either it's overridden (struck through), invalid (warning icon), inactive in that context, or a later state like :hover or a media query changes it. Check the Computed pane.
How do I debug a :hover or :focus style?
Force the state in DevTools with the :hov button, so it stays while you inspect.
Is * { outline: … } safe to leave in?
No, it's only for debugging. Load debug styles in development only.
Summary
- Ask in order: does the rule match, does it win, is the value valid, does the property apply, and is the layout doing something unexpected?
- Most bugs come from stacking contexts, indefinite heights,
min-width: auto, margin collapsing, containing blocks and overflow. - Outlines reveal boxes without changing layout; a script can list elements wider than the viewport.
- Debug selectors flag missing
alt, empty links and buttons, and inline styles. - Isolate with toggling, bisection and minimal reproductions.
- Layers, modules, tokens, intrinsic layout, fallbacks and testing prevent most bugs in the first place.
Practice questions
A dropdown with z-index: 1000 appears under a card with z-index: 2. The dropdown's parent has transform: translateZ(0). Explain and fix.
Answer
transform creates a stacking context, so the dropdown's z-index only orders it inside its parent. The parent itself has the default stack level and sits under the card. Remove the transform, or give the parent a position and z-index above the card's.
A sidebar has position: sticky; top: 0 but scrolls away. What do you check?
Answer
That an inset like top is set (it is), then whether an ancestor between the sidebar and the scrolling element has overflow: hidden, auto or scroll, which makes that ancestor the sticky element's scroll container. Also check that the sidebar's container is taller than the sidebar, or there's no room for it to stick.
The page scrolls sideways on phones. Write a console expression that lists the elements causing it.
Answer
[...document.querySelectorAll('*')].filter(el => el.getBoundingClientRect().right > document.documentElement.clientWidth);
Why is outline better than border for debugging layout?
Answer
Outlines are drawn outside the box model and take up no space, so adding them doesn't change sizes or positions. Borders add to the box, which can change the very layout you're debugging.
Review quiz
Test yourself on Part 17 with the CSS Part 17 review quiz.
Previous: CSS At-Rules Reference: @import, @namespace, @media, @supports, @layer and the Rest
Next: CSS Exercises: Beginner (Selectors, Cascade, Box Model and Color)

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.