What is CSS :target?
The CSS :target pseudo-class represents a unique element in a document: the one that matches the URL's fragment identifier. When a user clicks a link containing a hash (like #section) or navigates directly to a URL with a fragment, the browser scrolls to and highlights the matching element.
Understanding how :target works requires a brief exploration of URL fragment identifiers. A fragment identifier is the portion of a URL that follows the hash symbol (#), used to point to a specific section within a document. In HTML, elements can be targeted either by their id attribute or, in older implementations, by the name attribute. When a browser encounters a URL like https://example.com/page.html#features, it searches for an element with id="features" and makes it the active target. The :target pseudo-class then matches this element, allowing CSS rules to apply selectively based on navigation state.
The :target pseudo-class allows developers to style this target element, enabling a wide range of interactive behaviors without writing a single line of JavaScript. This selector has been part of CSS since early versions and enjoys universal browser support across all modern browsers, making it a reliable tool for creating accessible, performant user interfaces. Unlike JavaScript-based alternatives, :target requires no event listeners, no DOM manipulation, and adds zero bytes to your JavaScript bundle.
The no-JavaScript advantage means your interactive features work even when JavaScript is disabled, loads slowly, or fails to execute. This aligns perfectly with performance-first web development practices where minimizing client-side code leads to faster Time to Interactive and better Core Web Vitals scores.
1/* Target any element that is the URL fragment */2:target {3 outline: 3px solid #2563eb;4}5 6/* Target only heading elements that are targets */7h2:target {8 background-color: #fef3c7;9 padding: 0.5rem;10 margin-top: -0.5rem;11}12 13/* Target a specific element by ID */14#contact:target {15 border: 2px solid #059669;16}Common Use Cases
Single-Page Navigation Highlighting
One of the most practical applications of :target is creating navigation systems that indicate the currently viewed section in single-page layouts. When a user clicks a navigation link that points to an anchor on the same page, the corresponding section becomes the target. Using :target, developers can highlight this active section with background colors, borders, or other visual indicators that give users immediate feedback about their location within the page.
The implementation involves assigning unique IDs to each section and creating navigation links that point to these IDs. CSS rules then style the :target element differently from non-targeted sections, creating a clear visual distinction. For example, in a landing page built with modern CSS, you might assign IDs like #features, #pricing, and #contact to each section, then use CSS like section:target { background-color: #f0fdf4; border-left: 4px solid #16a34a; } to highlight the active section. This pattern eliminates the need for JavaScript event listeners and scroll position monitoring, resulting in a lighter-weight solution that works even when JavaScript is disabled. For more on CSS-only navigation patterns, see our guide to CSS selectors.
Table of Contents Active States
Documentation sites and long-form articles often include table of contents widgets that help users navigate quickly between sections. The :target pseudo-class enables an "active state" feature where the currently viewed section's entry in the table of contents receives special styling. When a user clicks a TOC link and the browser scrolls to that section, the corresponding TOC entry can be highlighted using CSS.
Implementation typically involves positioning the table of contents in a fixed sidebar and using adjacent sibling combinators or the :has() selector to connect the target section to its corresponding navigation item. This creates a seamless connection between the document structure and its navigation aid, improving the user's sense of orientation within lengthy content. For documentation-heavy websites like SaaS platforms or developer tools, this pattern significantly improves usability without adding JavaScript complexity.
Accordion and Tab Interfaces
The :target pseudo-class enables the creation of accordion and tabbed interface patterns without JavaScript. By using radio buttons with fragment identifiers or by targeting specific section IDs, developers can create panels that show or hide based on which element is currently targeted. This technique leverages the browser's native fragment navigation behavior to control visibility states.
The pattern involves creating a series of content panels, each with a unique ID, and providing activation links or buttons that point to these IDs. CSS hides all panels by default and shows only the one that matches :target, creating an immediate tab-switching effect purely through CSS. While this pattern does change the URL and affect browser history, it provides a viable alternative to JavaScript-controlled interfaces for simpler use cases. For progressive enhancement strategies, you can layer JavaScript on top to prevent URL changes while maintaining the CSS-only foundation.
Modal and Overlay Patterns
While modals typically require JavaScript for proper focus management and accessibility, the :target pseudo-class can create simple modal-like overlays for specific use cases. When a "view" link is clicked, it targets an overlay element's ID, and CSS displays the overlay in a fixed position covering the viewport. A close button within the overlay can simply link back to the page root or another non-modal URL, removing the target and hiding the overlay.
This pattern works well for simple dialogs, image lightboxes, and informational overlays where full accessibility support is not critical. The main advantage is simplicity--no JavaScript framework or event handling code is required. However, developers should be aware of limitations including the lack of focus trapping (a critical accessibility requirement for modals), the URL changing effect, and potential issues with browser back button behavior. For production applications requiring full accessibility compliance, JavaScript-based modals remain the recommended approach, but :target provides an excellent fallback or simple alternative.
Why Use CSS :target?
100%
Browser Support
0
JavaScript Required
Instant
Activation Speed
0KB
Bundle Impact
Performance Benefits
The :target pseudo-class offers significant performance advantages over JavaScript-based alternatives for several reasons. First, it requires no JavaScript execution, eliminating the overhead of event listener registration, callback execution, and DOM manipulation. The browser's native URL fragment handling triggers the styling changes as part of the browser's core navigation behavior, which is highly optimized across all modern engines. This means :target styling activates instantly when a fragment changes, without waiting for JavaScript to execute.
Second, :target does not contribute to JavaScript bundle size, which is increasingly important for performance metrics like Core Web Vitals. Every kilobyte of JavaScript affects parsing time, compilation time, and execution time--all of which impact page interactivity and perceived performance. By using CSS-only solutions where appropriate, developers can keep their JavaScript bundles smaller and their sites faster. This aligns with the performance optimization strategies that prioritize efficient code delivery.
Third, :target works regardless of JavaScript availability. In environments where JavaScript is disabled, blocked, or fails to load, :target-based navigation continues to function normally. This graceful degradation is valuable for accessibility, performance on constrained devices, and users who intentionally disable JavaScript for privacy or security reasons. For teams focused on web accessibility best practices, this built-in accessibility makes :target an excellent choice.
:target vs JavaScript: When to Use Each
| Criterion | :target | JavaScript |
|---|---|---|
| Bundle Size | No impact | Adds to bundle |
| Activation Speed | Native, instant | Event-driven, slight delay |
| Focus Trapping | Not supported | Full support |
| URL Changes | Yes (fragment only) | Optional |
| Browser History | Affected | Can be controlled |
| Accessibility | Basic | Full ARIA support |
| Animation Control | CSS transitions only | Full control |
Prefer :target when the interaction pattern aligns with natural fragment navigation, universal browser support is required without polyfills, minimizing JavaScript bundle size is a priority, and accessibility requirements for focus management do not mandate JavaScript intervention.
Consider JavaScript-based alternatives when focus trapping is required (as in modals and dialogs), when the interaction pattern should not affect browser history or URLs, when animations require precise control beyond CSS capabilities, when supporting SPA contexts where fragment changes might conflict with routing logic, and when full accessibility support including screen reader announcements is required.
1/* Ensure targeted content appears below fixed headers */2:target {3 scroll-margin-top: 80px;4}5 6/* Add extra margin for section headings */7h2:target {8 scroll-margin-top: 100px;9}10 11/* Style all targets except navigation elements */12:target:not([id^="nav"]) {13 background-color: #eff6ff;14}Best Practices and Accessibility
Providing Visual Focus Indicators
One of the primary purposes of :target is to draw attention to the element that was navigated to, which aligns well with accessibility requirements for visible focus indicators. When users navigate via fragment links, they should clearly see which element received focus. Using :target with prominent visual styles--such as background colors, borders, or box shadows--helps users with cognitive disabilities and those using screen magnifiers understand where they have landed on the page. Avoid subtle styling that might be missed by users with visual impairments.
Managing Scroll Behavior
Use scroll-margin-top to add an offset to the scroll position. This is essential when pages have fixed headers that would otherwise obscure the beginning of targeted content. Setting scroll-margin-top on targeted elements ensures the content appears below fixed headers, improving usability and accessibility for all users.
Accessibility Checklist for :target
- Visual Feedback: Ensure targeted elements have clear visual indicators (background color, border, or outline)
- Scroll Margin: Add
scroll-margin-topto prevent fixed headers from obscuring content - Skip Links: Provide skip navigation links for keyboard users to bypass repetitive content
- Focus Management: For modals and overlays, consider how focus should be handled when closing
- Color Contrast: Maintain WCAG AA contrast ratios for target styling colors
- Reduced Motion: Respect
prefers-reduced-motionwhen animating target transitions
Fallback Considerations
While :target has universal browser support in modern browsers, providing fallback styling for edge cases ensures consistent experiences. When :target cannot activate (such as on initial page load without a fragment in the URL), consider how elements should appear by default. CSS custom properties and progressive enhancement techniques can help create experiences that work with or without target styling, ensuring no user is left with a broken visual state.
Powerful techniques for sophisticated CSS-only interfaces
Documentation Grids
Create interactive grids where clicking a topic highlights its corresponding content area. Works perfectly for API docs and component libraries.
Step Wizards
Build multi-step forms where each step shows based on fragment targeting. Great for lead generation and checkout flows.
Image Galleries
Implement lightweight lightbox galleries using :target for full-size image display. No JavaScript required.
Navigation Indicators
Show active states in sidebars and TOC widgets without JavaScript. Essential for documentation sites.