← All Examples

Modal Dialog

A modal using :target to show/hide without JavaScript.

Published May 19, 2026

Demo

Open Modal

HTML

<a href="#my-modal">Open Modal</a>

<div class="modal-overlay" id="my-modal">
  <div class="modal-box">
    <h3>Modal Title</h3>
    <p>Modal content here.</p>
    <a href="#">Close</a>
  </div>
</div>

CSS

.modal-overlay {
  display: none;
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,.5);
  z-index: 200;
  align-items: center;
  justify-content: center;
}

.modal-overlay:target {
  display: flex;
}

.modal-box {
  background: #fff;
  border-radius: 12px;
  padding: 2rem;
  max-width: 400px;
}

How it works

The :target pseudo-class matches an element whose id matches the URL fragment. Clicking the open link sets the URL hash, which makes :target match and shows the overlay. Clicking the close link clears the hash (href="#"), hiding the modal. The overlay is display:none by default and display:flex when :target.