How to debug CSS when your layout looks wrong
CSS problems can feel mysterious: an element won't center, a gap appears from nowhere, something overflows the screen. A methodical approach makes them much easier.
1. Inspect the element
Right-click and choose Inspect. DevTools shows which CSS rules apply, which are overridden (crossed out) and where each comes from.
2. Check the box model
The box model diagram in DevTools shows content, padding, border and margin. Unexpected space is often margin, sometimes from collapsing margins between elements.
3. Outline everything
Temporarily add * { outline: 1px solid red; } to see every element's boundaries. Outlines don't affect layout, unlike borders.
4. Check display and layout context
- Is the parent using flexbox or grid? DevTools has overlays for both.
- Is the element inline, block or something else? Inline elements ignore width and vertical margins.
5. Look for common culprits
- Overflow: a fixed width or a long word or image wider than the screen. Find which element is wider than the viewport.
- Specificity conflicts: a more specific selector overrides yours.
box-sizing: settingbox-sizing: border-boxmakes widths include padding and border, which is usually more intuitive.- Positioning:
absoluteelements position relative to the nearest positioned ancestor. - z-index: only works within stacking contexts, which other properties can create.
6. Reduce the problem
Remove styles or elements until it behaves, then add back one at a time.
What CSS bug took you the longest to figure out? Which DevTools feature helps you most?
Comments · 2
Add a temporary outline to every element. You see the box model instantly and can spot what's pushing things around.
Browser dev tools have a layout view for flexbox and grid now. Seeing the overlay explains most surprising gaps.