CSS Image Modal

Create an image modal (lightbox) using CSS with the :target technique, including overlay, centering, and close button.

On this page

Image Modal

An image modal (often called a lightbox) displays a larger version of an image on top of the page with a dark overlay behind it.

You can build a simple CSS-only modal using the :target selector. It works by linking to an element id (like #img1) and showing the modal when that element becomes the URL target.

Open/Close with :target

Thumbnail links to the modal id:

<a href="#img1" class="thumb">
  <img src="small.jpg" alt="Preview">
</a>

<div id="img1" class="modal">
  <a href="#" class="modal-close">&times;</a>
  <img class="modal-content" src="large.jpg" alt="Large">
</div>

Clicking the thumbnail changes the URL hash to #img1. The modal is hidden by default, and becomes visible when targeted.

Styling the Modal

Basic overlay and center positioning:

.modal {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,.75);
  display: flex;
  align-items: center;
  justify-content: center;

  opacity: 0;
  pointer-events: none;
  transition: opacity .2s ease;
}

.modal:target {
  opacity: 1;
  pointer-events: auto;
}

Modal image sizing:

.modal-content {
  max-width: min(90vw, 1000px);
  max-height: 85vh;
  border-radius: 12px;
  box-shadow: 0 18px 50px rgba(0,0,0,.35);
}

Close button:

.modal-close {
  position: absolute;
  top: 18px;
  right: 22px;
  font-size: 38px;
  line-height: 1;
  color: #fff;
  text-decoration: none;
  opacity: .85;
}

.modal-close:hover {
  opacity: 1;
}

Optional: Add a subtle zoom-in animation:

.modal-content {
  transform: scale(.96);
  transition: transform .2s ease;
}

.modal:target .modal-content {
  transform: scale(1);
}

Tip: The :target approach is lightweight and works without JavaScript, but it also changes the URL hash. If you want a modal that does not affect the URL, you typically use JavaScript.

Summary

  • An image modal shows a large image above a dim overlay.
  • With CSS, you can build a simple lightbox using :target.
  • Use position: fixed + inset: 0 for the overlay and flexbox for centering.
  • Use opacity + pointer-events to hide/show smoothly.

CSS Image Modal Examples (9)