CSS :target Pseudo Class

CSS :target Pseudo Class

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

selector:target { property: value; }

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

<h2 id="section1">Section 1</h2> <p>Content of Section 1...</p> <h2 id="section2">Section 2</h2> <p>Content of Section 2...</p> <a href="#section2">Go to Section 2</a>
h2:target { background-color: yellow; transition: background 0.5s; }

✅ Clicking "Go to Section 2" highlights "Section 2" with a yellow background.

4. Example – CSS-Only Modal with :target

<a href="#popup">Open Modal</a> <div id="popup" class="modal"> <div class="content"> <a href="#">Close</a> <p>This is a CSS modal!</p> </div> </div>
.modal { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); } .modal:target { display: block; }

✅ Clicking "Open Modal" shows the modal.
✅ Clicking "Close" removes #popup from the URL, hiding the modal.

5. Example – Tabs Using :target

<a href="#tab1">Tab 1</a> <a href="#tab2">Tab 2</a> <div id="tab1" class="tab-content">Content for Tab 1</div> <div id="tab2" class="tab-content">Content for Tab 2</div>
.tab-content { display: none; } .tab-content:target { display: block; }

✅ 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close