CSS by Patrik

Smart Spacing for Headings in CSS

Introduction

Good spacing makes a page easier to read and more pleasant to scan. But adding space before every heading can create unwanted gaps — especially when headings follow each other or appear at the top of a section. In this guide, you’ll learn a simple CSS technique to add space before headings only when it actually improves readability.

The Idea

We want to add top spacing to headings when:

  • The heading is not the first element in its container
  • The element before it is not another heading

This keeps related headings visually grouped while still separating them from normal content like text, images, or lists.

The Solution

Use the adjacent sibling selector (+) together with :not() to target only the headings that need spacing:

.app :not(h1, h2, h3) + h1,
.app :not(h1, h2, h3) + h2,
.app :not(h1, h2, h3) + h3 {
  margin-top: 20px;
}
How it works:
  • :not(h1, h2, h3) selects any element that is not a heading.
  • + h1, + h2, + h3 selects a heading that comes directly after that element.
  • The margin is applied only in this situation.

This means:

  • A heading after text gets spacing
  • A heading after another heading stays close
  • The first heading in a container gets no extra space

Optional: Different Spacing per Heading

You can fine-tune the spacing for each heading level:

.app :not(h1, h2, h3) + h1 { margin-top: 32px; }
.app :not(h1, h2, h3) + h2 { margin-top: 24px; }
.app :not(h1, h2, h3) + h3 { margin-top: 16px; }

This gives you more control over visual hierarchy.

Why This Is Useful

  • Improves readability and visual structure
  • Avoids unnecessary empty space
  • Keeps your layout clean and consistent
  • Works in all modern browsers

A small CSS rule like this can make a big difference in how professional and readable your pages feel.

CSS
layout
spacing
selectors
frontend

Comments