CSS :target Selector
The :target pseudo-class is used to style an element when its ID matches the current URL fragment.
It works with:
[code theme="dark"]
#id
[/code]
in the browser URL.
The:
[code theme="dark"]
:target
[/code]
selector is commonly used for:
- Page navigation
- Anchor scrolling
- FAQ accordions
- Highlighting sections
- Modal popups without JavaScript
[grid]
Anchor Navigation Demo
FAQ Target Example
Section Highlighting
Modal Popup Using :target
[/grid]
How :target Works
When a URL contains:
[code theme="dark"]
#section
[/code]
the element with:
[code theme="dark"]
id="section"
[/code]
becomes the active target.
Basic Syntax
[code theme="dark"]
:target{
styles
}
[/code]
Simple Example
[code theme="dark"]
#about:target{
background:#dbeafe;
}
[/code]
When:
[code theme="dark"]
#about
[/code]
appears in the URL, the section becomes highlighted.
HTML Structure
[code theme="dark"]
Go To About
[/code]
Live Navigation Demo
Target Section 1
Target Section 2
FAQ Accordion Example
The:
[code theme="dark"]
:target
[/code]
selector can create simple accordions without JavaScript.
[code theme="dark"]
#faq1:target{
display:block;
}
[/code]
HTML Structure
[code theme="dark"]
Open FAQ
FAQ Content
[/code]
Live Demo
Open FAQ
This content becomes visible when targeted.
Modal Popup Example
CSS-only modal systems can also use:
[code theme="dark"]
:target
[/code]
[code theme="dark"]
#modal:target{
opacity:1;
visibility:visible;
}
[/code]
HTML Structure
[code theme="dark"]
Open Modal
Modal Content
[/code]
Live Demo
CSS Target Modal Content
:target vs JavaScript
|
Feature
|
:target
|
JavaScript
|
|
Requires JavaScript
|
No
|
Yes
|
|
Dynamic Control
|
Limited
|
Advanced
|
Advantages of :target
- No JavaScript required
- Simple interactive UI
- Useful for anchor navigation
- Lightweight solution
- Easy to implement
Disadvantages
- Only one target can be active at a time
- Changes browser URL
- Limited compared to JavaScript interactions
Cross Browser Compatibility
The:
[code theme="dark"]
:target
[/code]
selector is fully supported across all modern browsers.