CSS :target Selector

❮ Previous Selectors Next ❯

Example

:target {
  background-color: gold;
}

Meaning

The :target selector selects a unique element (the target element) with an id matching the URL's fragment.

Version: CSS3




Standard Syntax

:target {
  css declarations;
}



Browser Support

The numbers in the table specify the first browser version that fully supports the property.




Status










Pure-CSS lightbox

You can use the :target pseudo-class to create a lightbox without using any JavaScript.

This technique relies on the ability of anchor links to point to elements that are initially hidden on the page. Once targeted, the CSS changes their display so that they are shown.

Example

/* Unopened lightbox */
.lightbox {
  display: none;
}

/* Opened lightbox */
.lightbox:target {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Lightbox content */
.lightbox div {
  width: 25rem;
  max-width: 80%;
  position: relative;
  padding: 1.5em;
  background-color: #1A73E8;
  border-radius: 4px;
  color: white;
}

/* Close button */
.lightbox .close {
  position: relative;
  display: block;
}

.lightbox .close::after {
  right: -1rem;
  top: -1rem;
  width: 2rem;
  height: 2rem;
  position: absolute;
  display: flex;
  z-index: 1;
  align-items: center;
  justify-content: center;
  background-color: black;
  border-radius: 50%;
  color: white;
  content: "×";
  cursor: pointer;
}
❮ Previous Selectors Next ❯