company logo

Before you start

Components List

Navigation

Data Display

Forms

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

<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Static Site</title>
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <button class="open-btn">Click me to open modal</button>
    
        <!-- modal container -->
        <div class="modal hide">
            <div>
                <p class="title">Title of modal goes here</p>
                <p class="text">Supporting text right here</p>
            </div>
            <button>Click me please!</button>
            <span class="close-btn">&times</span>
        </div>
    
        <div class="overlay hide"></div>
    <script src="script.js"></script>
    </body>
    </html>

* 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 &times 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!

Made by Sam Kotecha

linkedin logo