Creating a Modal using HTML, CSS, and Javascript
What you'll learn
- DOM Manipulation and Event Handling
- Flexbox
- CSS Positioning
- How to create an overlay
Prerequisites
- Basic HTML, CSS, and Javascript
- Completed the Card tutorial
React verison coming soon!
The Code
* If the component preview isn't loading, try refreshing the page.
* You can adjust the size of the code preview and code by draging the sides!
Explanation
HTML
- First let's create a button to open our modal. Then, we'll create a modal container with a simple heading, a supporting tag, a button, and a close button. You can create a close button in HTML with × in a <span>.
- Notice the lonely div at the bottom with the class overlay. We will create a light overlay to make the modal really stand out when opened.
CSS
- Our modal will have some basic styling, but notice we position the modal in the center. We used a position value of fixed, with top:50% and left:50%, and transform, to center the modal on the page. This is a common way to center something on the page. Our modal will also have a high z-index, making sure it sits on top of all content, including our overlay.
- We do the same for our open button.
- Our overlay is styled to fill the whole screen with the position and its corresponding values. Its z-index is also high but not higher than our modal, so it covers everything but our mdoal
- Finally, we have two classes to hide both our overlay and our modal
Javascript
- For our JS, we get the following elements and store them into JS variables: our open button, modal, modal close button, and our overlay.
- We add a basic event listener of click for our open button, removing the hidden classes from both the overlay and modal.
- If the x button is clicked, we do the opposite and add these classes back, that's it!