Simple Modal Using CSS Only

Simple Modal Using CSS Only
Project: Basic CSS-Only Modal
Author: Timothy Long
Edit Online: View on CodePen
License: MIT

This code helps you to create a simple modal window functionality using CSS only. It defines the styles and behaviors for the modal window, making it appear and disappear when triggered. The modal is opened by activating the :target pseudo-class when the link with the corresponding modal ID is clicked, and it is closed by unchecking the associated checkbox input.

This code offers a straightforward and lightweight approach to implement modals without the need for JavaScript. It can be useful for scenarios where a simple modal window is required, such as displaying additional information, confirmation dialogs, or interactive overlays in web applications.

How to Create a Simple Modal Using CSS Only

1. Use the following HTML structure for the modal dialog box:

<div class="container">
  <div class="interior">
    <a class="btn" href="#open-modal">👋 Basic CSS-Only Modal</a>
  </div>
</div>
<div id="open-modal" class="modal-window">
  <div>
    <a href="#" title="Close" class="modal-close">Close</a>
    <!-- Your Modal Content Goes Here -->
  </div>
</div>
</div>

2. Apply the following CSS styles to create the modal functionality:

.modal-window {
  position: fixed;
  background-color: rgba(255, 255, 255, 0.25);
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  visibility: hidden;
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s;
}
.modal-window:target {
  visibility: visible;
  opacity: 1;
  pointer-events: auto;
}
.modal-window > div {
  width: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 2em;
  background: white;
}
.modal-window header {
  font-weight: bold;
}
.modal-window h1 {
  font-size: 150%;
  margin: 0 0 15px;
}

.modal-close {
  color: #aaa;
  line-height: 50px;
  font-size: 80%;
  position: absolute;
  right: 0;
  text-align: center;
  top: 0;
  width: 70px;
  text-decoration: none;
}
.modal-close:hover {
  color: black;
}

That’s it! You have successfully created a simple modal using CSS only. This approach is lightweight and doesn’t require JavaScript, making it ideal for scenarios where a basic modal window is needed, such as displaying additional information, confirmation dialogs, or interactive overlays in web applications.

Feel free to comment below if you have any questions or suggestions.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply