1 min read

CSS :target Pseudo-class

The :target pseudo-class represents a unique element (the target element) with an id matching the URL's fragment. It allows you to style an element based on the current hash in the URL.

1. The Concept

When a URL ends with a fragment identifier (e.g., http://example.com/#contact), the element on the page with id="contact" is the target element. The :target selector allows you to apply styles specifically to that element.

2. Basic Usage

This is often used to highlight a section when a user clicks a "Jump to" link.

section:target {
  background-color: yellow;
  border: 2px solid orange;
}
<a href="#section1">Go to Section 1</a>
<a href="#section2">Go to Section 2</a>

<section id="section1">Section 1</section>
<section id="section2">Section 2</section>

3. Use Case: Pure CSS Modals

You can create modals that open and close without JavaScript using :target.

  1. Open: Link points to the modal's ID (href="#modal").
  2. Close: Link inside modal points to # or another ID (href="#").
.modal {
  display: none; /* Hidden by default */
  position: fixed;
  top: 0; left: 0; width: 100%; height: 100%;
  background: rgba(0,0,0,0.5);
}

/* Show when targeted */
.modal:target {
  display: block;
}
<a href="#my-modal">Open Modal</a>

<div id="my-modal" class="modal">
  <div class="modal-content">
    <p>Hello!</p>
    <a href="#">Close</a>
  </div>
</div>

4. Pros and Cons

  • Pros: No JavaScript required. Deep linking works automatically (sending the URL opens the modal/tab).
  • Cons: It affects the browser history (Back button closes the modal). It causes the page to jump/scroll to the target element (unless prevented).

programming/css/css programming/css/pseudo-classes-and-pseudo-elements programming/css/selectors