How to Make a Simple Modal Window

By everybody , aka mind Simple Modal Window

Modal windows can be a bit tricky to get up and running, so we are going to go over how to create a simple modal window with only HTML and CSS. No Javascript required! Commonly, modal windows are created using JavaScript or JQuery, but they don’t need to be. Our alternative is simple, lightweight, and only has around 30-ish lines of code to it!

1. Set Up the HTML and Hide the Box

The HTML for our modal window, and the links to open and close it, look like this:

<a href="#modalWindow">Modal Window</a>
<div id="modalWindow" class="modalBox">
  <div>
    <a class="closeWindow" href="#close">X</a>
    <p>Modal Window</p>
  </div>
</div>

The outer div represents the modal window’s entire layer (including the translucent background behind it). The inner div contains the actual modal box that appears in the center of the screen. That is all the HTML required! Now let’s take a look at the styling for our Modal Window layer:

.modalBox {
  position: fixed; /* create the modal window layer, and have it fill the entire screen */
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background: rgba(0,0,0,0.8); /* set the modal window layer's background color to a translucent black */
  z-index: 99999; /* put the layer on top of every other layer */
  opacity:0; /* make the layer invisible intially */
  pointer-events: none;
}

2. Add Open and Close Triggers

All of the action will happen in :target within our CSS, so that when our modal window layer becomes the active target (by click on the link to open it), all of the styles defined there will take place. This also means that when the layer is no longer targeted (when you click the close link), all of the CSS styles defined there will be removed. Basically, our class extension should look something like this:

.modalBox:target {
  opacity:1; /* make the modal window layer visible */
  pointer-events: auto;
}

3. Define Size and Position

This takes us to our last snippet of CSS, where we define the size and position of the window itself. All of those styles will go in a CSS definition that looks like this:

.modalBox > div {
  width: 500px; /* set the window's width */
  position: relative;
  margin: 10% auto; /* center the window horizontally */
  padding: 5px;
  background: #fff;
}

Put all of those pieces together, and you’ve made yourself a simple modal window! Check out the Live Demo to see for yourself.

Check out our other posts to learn more cool stuff about web design and development, or you can always contact us to handle your custom projects. Comment below and share this post if you found it helpful!

View Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Are You Ready To Do More with Mind?

Click the link below to get started!

Work With Mind