Theme & Front End CSS Beginner

Stop Sticky Headers Covering Anchor Targets

Leave space above headings when visitors jump to them, so a fixed or sticky header doesn't hide them.

Tested on WordPress 7.1 No plugin needed Updated
style.css 8 lines
:target,
h1[id],
h2[id],
h3[id],
h4[id] {
	/* The height of your sticky header, plus a little breathing room. */
	scroll-margin-top: 100px;
}

Where to add this

Recommended Additional CSS Appearance → Customize → Additional CSS, or your page builder's global CSS.
Child theme At the end of your child theme's style.css file.
A code snippets plugin As a CSS snippet set to load on the front end.

With a sticky header, clicking a table of contents link or opening a URL with a #section scrolls the heading right to the top of the window, where the header covers it. This CSS fixes that.

How it works

scroll-margin-top adds an offset to an element whenever the browser scrolls it into view. It works for anchor links, #hash URLs, and scripts using scrollIntoView(). The rule applies to headings with an id, which are what tables of contents link to, and to whatever the current URL’s hash points at.

Things to watch

  • Set the value to your header’s height. If it shrinks on scroll, use the smaller height.
  • When logged in, the admin bar adds another 32 pixels. You can add .admin-bar :target { scroll-margin-top: 132px; } for that.

How to test it

Open a post with a table of contents and click a link. The heading should land just below the header, fully visible.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only