Modal through HTML, CSS and JavaScript

What is Modal in webpage? How to make a Modal through HTML, CSS and JavaScript?

Last updated:7/20/2021 1:25:09 AM

1 Answers

Ethan Karla
Ethan Karla

A modal (also called a modal window or lightbox) is a web page element that is displayed and disabled in front of all other page content. To return to the main content, the user must engage with the modal by completing an action or closing it. Models are often used to direct users' attention to some important action or information on a website or application.

Let's have a look on the below code :

<!DOCTYPE html>

    <meta name='viewport' content='width=device-width, initial-scale=1'>
        body {
            font-family: Arial, Helvetica, sans-serif;
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            padding-top: 100px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgb(0,0,0);
            background-color: rgba(0,0,0,0.4);
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            .close:focus {
                color: #000;
                text-decoration: none;
                cursor: pointer;
    <h2>Modal Example</h2>
    <button id='myBtn'>Open Modal</button>
    <div id='myModal' class='modal'>
        <div class='modal-content'>
            <span class='close'>&times;</span>
            <p>Some text in the Modal..</p>
        var modal = document.getElementById('myModal');
        var btn = document.getElementById('myBtn');
        var span = document.getElementsByClassName('close')[0];
        btn.onclick = function () {
   = 'block';
        span.onclick = function () {
   = 'none';
        window.onclick = function (event) {
            if ( == modal) {
       = 'none';

Hope this code will be helpful for you.

Happy Coding!