Making a Simple Modal Window

Modal windows can be a bit tricky to get up a 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, light weight, and only has around 30-ish lines of code to it!

Setting Up The HTML And Hiding 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">
    <a class="closeWindow" href="#close">X</a>
    <p>Modal Window</p>

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;

Adding 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;

Which takes us to our last snippet of CSS, where we define the size and position of our modal 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;

Pulling It Together

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!

Leave a Reply

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