:target

Matches the element referenced by a URL fragment. Highlights the element when directly linked to.

Quick example

:target { background-color: yellow; }
:target-within { outline: 2px solid blue; }

Examples

Highlight the targeted section

section:target {
  background-color: #ffffcc;
  border-left: 4px solid #ff9800;
}

/* Visited via #section-id in URL */

Highlight the section that's linked via URL fragment, drawing attention to the target.

Show/hide panels based on URL fragment

.panel { display: none; }
.panel:target { display: block; }

/* Panels show only if URL contains #panel-id */

Use :target to build bookmark-able accordion or tabbed interfaces without JavaScript.

Scroll to and highlight in one step

#search-result:target {
  scroll-margin-top: 5rem;
  background-color: #e8f5e9;
  border: 2px solid green;
}

Browser scrolls to the target and :target styling makes it stand out immediately.

:target Browser Support

Widely available Since 2002 95% global usage

This feature is well established and works across many devices and browser versions. It has been available across browsers since 2002.

Safe to use without fallbacks.

Common pitfalls

:target only works with URL fragments

:target matches elements whose id matches the URL hash. If there's no #fragment in the URL, :target matches nothing.

Styles reset when navigating away

When the user clicks to a different fragment, the old :target styles remove instantly and new ones apply. This can feel jarring; consider transition: background-color 0.3s.

Conflicts with JavaScript routing

If your app uses JavaScript to change hash without page reload, ensure your JS triggers the same visual changes as :target would.

ESC