Creating a modal window without using JavaScript
Have you often wanted to create a modal window (a window that opens within your website) but don't know JavaScript? Let’s discover together how to successfully achieve this!
Step 1
Let's start with the HTML code.
<a href="#demo">Open Modal</a>
<div id="demo" class="modal">
<div class="modal_content">
<h1>Hello</h1>
<p>Welcome to the modal window!</p>
<a href="#" class="modal_close">×</a>
</div>
</div>
The anchor of our link (#demo
) serves as a reference to the id that will be on our modal window.
Step 2
Let's style the link.
a {
text-decoration: none;
padding: 15px;
background-color: white;
border-radius: 5px;
text-transform: uppercase;
color: black;
}
Step 3
Let's take care of the modal window.
.modal {
visibility: hidden;
opacity: 0;
position: absolute;
top: 0; right: 0;
bottom: 0; left: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(77, 77, 77, .7);
transition: all .4s;
}
Step 4
Let's detect the click!
.modal:target {
visibility: visible;
opacity: 1;
}
It's thanks to the target pseudo-class that we can do without JavaScript!
Step 5
Let's style the content of the modal to finish.
.modal_content {
border-radius: 4px;
position: relative;
width: 500px;
max-width: 90%;
background: white;
padding: 1.5em 2em;
}
.modal_close {
position: absolute;
top: 10px;
right: 10px;
color: grey;
text-decoration: none;
}