What it is and why to use it
:target selects the element identified by the current document URL’s fragment. It is useful for highlighting a section after a reader follows a table-of-contents link. The selector responds to navigation state without requiring JavaScript to add a class.
Common mistakes and limitations
A target is not necessarily the keyboard-focused element. Keep focus styling separately. IDs must be unique within the document, and essential information must not depend only on the target colour. Preview fragment links apply within the sandbox document.
Try the example
The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.
HTML used by this example
<a href="#intro">Highlight introduction</a><section class="lesson" id="intro"><h3>Introduction</h3><p>This section becomes the URL target.</p></section>Syntax
:target { outline: 3px solid currentColor; }Examples
Highlighting Fragment Targets with :target
Run the CSS against the supplied HTML, then experiment with the values.
.lesson { padding: 1rem; border: 1px solid #94a3b8; }
.lesson:target { background: #dbeafe; color: #172b4d; outline: 3px solid #2563eb; outline-offset: 2px; }- The link sets the document fragment to intro.
- The section with that id matches :target and receives the highlight.
- Changing the fragment changes the matching element. This is useful for helping readers locate a linked passage after navigation.
HTML used by this example
<div class="demo"><a href="#intro">Highlight introduction</a><section class="lesson" id="intro"><h3>Introduction</h3><p>This section becomes the URL target.</p></section></div>Best practices
- A target is not necessarily the keyboard-focused element. Keep focus styling separately. IDs must be unique within the document, and essential information must not depend only on the target colour. Preview fragment links apply within the sandbox document.
- Inspect the relevant browser reference and test the browsers used by your audience.
Runtime & versions
Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
CSS specifications (modules)