<button type="button" class="open-modal">Open modal</button>
<div class="modal-outer is-hidden">
<div class="modal-inner">
<button type="button" class="modal-close">×</button>
<h1>Modal content</h1>
<p>You can click anywhere outside the modal to close it.<br>Alternatively, there's the close button in the upper right corner.</p>
</div>
</div>
body {
margin: unset;
font: normal 16px/1.5 Gelasio, serif;
text-align: center;
}
.open-modal {
font-family: inherit;
font-size: 23px;
background-color: tomato;
border: none;
font-weight: bold;
padding: .5rem 4rem;
border-radius: .2rem;
margin-top: 3rem;
cursor: pointer;
}
.open-modal:hover {
background-color: black;
color: white;
}
.modal-outer {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(200, 200, 200, .4);
display: flex;
align-items: center;
justify-content: center;
}
.modal-outer.is-hidden {
display: none;
}
.modal-inner {
background-color: white;
position: relative;
box-shadow: 0 10px 20px -10px rgba(0, 0, 0, .1);
width: 100%;
max-width: 70vw;
max-height: 50vh;
border-radius: .5rem;
padding: 2rem;
box-sizing: border-box;
text-align: center;
}
.modal-close {
position: absolute;
top: 0;
right: 0;
font-size: 2rem;
background-color: transparent;
border: none;
margin: unset;
width: 50px;
height: 50px;
cursor: pointer;
}
.modal-close:hover,
.modal-close:focus {
color: tomato;
}
(function() {
"use strict";
var modal = document.querySelector(".modal-outer");
var open = document.querySelector(".open-modal");
var close = modal.querySelector(".modal-close");
function handleModalOpen() {
modal.classList.remove("is-hidden");
}
function handleModalClose() {
modal.classList.add("is-hidden");
}
function handleModalClick(evt) {
if (!evt.target.closest(".modal-inner")) {
handleModalClose();
}
}
function handleKeyDown(evt) {
if (evt.key == "Escape" && !modal.classList.contains("is-hidden")) {
handleModalClose();
}
}
open.addEventListener("click", handleModalOpen);
close.addEventListener("click", handleModalClose);
modal.addEventListener("click", handleModalClick);
window.addEventListener("keydown", handleKeyDown);
})();
This Pen doesn't use any external JavaScript resources.