CSS Only Modal

Experiments in a JavaScript free webpage

12 Apr 2019

The CSS modal is a topic that has been discussed much before online for a few years. This is my take on it.

Simply it is achieved by having a hidden check-box and a selection of labels for that check box that are used as buttons. Here is a simple implementation:

Markup

We have a lable that can be placed anywhere on the page to open the modal. There can be as many as you want. The for informs the browser which check box it is for, in the case of my gallery pages I use generated ids and for to allow for mutple on a page.

<label for="modal_12345" class="modal_button">Click Me!</label>

Then, where you want the modal to appear I put in a div for readability and as container for css selectors. Inside that div goes the checkox itself. It is important it comes first.

<div>
    <input type="checkbox" id="modal_12345" autocomplete="off" class="modalToggle">
    <label class="modalCloser" for="modal_12345"></label>
    <div class="modal">
        <div class="modal__content">
            <div> <label for="modal_12345" class="close_button">&#215;</label> </div>
            <p>Modal Content Goes here </p>
        </div>
    </div>
</div>

That’s it for the markup. The modalCloser is so that users can click outside the modal and have it close. For modals that you don’t want that behaviour do not include it.

CSS

.modal {
    display: none;
    position: fixed;
    z-index: 100;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    align-items: center;
    justify-content: center;
    pointer-events: none;
}

.modal * {
    pointer-events: initial;
}

.modal__content {
    box-sizing: border-box;
    overflow: auto;
    max-height: 90vh;

    padding: 20px;
    background-color: #fff;
}

.modalToggle {
    display: none;
}

.modalToggle:checked~* {
    display: flex;
}

This is the core of all that you need. You will obviously want to style the buttons too and . the .modal__content to look the way you want it to.

The .modalToggle:checked~* selector says to the browser to take everything over the checkbox and apply this rule—making it display: flex;—when the checkbox is checked.

Most of css content is make the modal appear over the main content and be fixed.

Lastly if you want to have the modal be closeable by clicking ooutside you’ll need this style:

.modalCloser {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, .65);
    cursor: pointer;
}

Caveats

The only catch here that there is no animation, this can be overcome by some tricks with visibility: hidden and related things. I didn’t see this as a big enough problem for my uses. Also, due to the way CSS works—by never looking back up the tree—it makes it impossible to prevent scrolling on body like most Javascript modals will. Again I found this ok.

Give it a try!