CSS :target
Pseudo-Class
The :target
pseudo-class in CSS applies styles to an element when its ID is targeted by a URL fragment (#id
). It’s commonly used for in-page navigation, modals, and tabs without JavaScript.
1. Syntax
2. How :target
Works
When you click a link with #id
, the element with that id
is targeted, and the styles defined under :target
are applied.
3. Example – Highlighting a Targeted Section
✅ Clicking "Go to Section 2" highlights "Section 2" with a yellow background.
4. Example – CSS-Only Modal with :target
✅ Clicking "Open Modal" shows the modal.
✅ Clicking "Close" removes #popup
from the URL, hiding the modal.
5. Example – Tabs Using :target
✅ Clicking "Tab 1" shows Tab 1 content, hiding others.
6. Best Practices
✔ Use :target
for smooth navigation without JavaScript.
✔ Combine with transition
for better animations.
✔ Use :target
for modals, tabs, accordions, and page sections.