Others




Create Simple Modal Using CSS and JavaScript


A Modal is a popup window build by HTML,CSS and JavaScript. The following example shows how to create simple modal using CSS and JavaScript. We have to open and close the modal using JavaScript Functions.

Example : modal.html
<html>
  <head>
    <title>Model Using CSS JavaScript</title>
    <style>
      body{
        margin:0;
        text-align:center;
      }
      .container{
        width:80%;
        margin:auto;
        line-height:1.6em;
        font-size:1.2em;
        padding:10px 0px;
      }
      .btn{
        border:1px solid black;
        border-radius:2px;
        background:white;
        color:#000;
        font-weight:700;
        font-size:.7em;
        padding:10px 13px;
      }
      .model{
        position:absolute;
        background:rgba(0,0,0,80%);
        width:100%;
        height:100%;
        z-index:1000;
        top:0;
        left:0;
        display:none;
      }
      .model-dialog{
        text-align:left;
        width:400px;
        height:auto;
        background:white;
        margin:auto;
        padding:15px 25px;
        border-radius:8px;
        position:relative;
        line-height:1.5em;
        -moz-animation-name:move;
        -moz-animation-duration:2s;
        -moz-animation-fill-mode:forwards;
        animation-name:move;
        animation-duration:2s;
        animation-fill-mode:forwards;
      }
      .model hr{
        border:none;
        height:1px;
        background:#ccc;
      }
      .close{
        cursor:pointer;
        border:none;
        background:none;
        font-weight:700;
        font-size:1.1em;
        position:absolute;
        right:30px;
        top:40px;
      }
      @keyframes move{
        0% {top:-100%;}
        100% {top:20px;}
      }
    </style>
  </head>
  <body>
    <div class='container'>
      <h1>Model Using CSS JavaScript</h1>
      <input type='button' value='Show Model' class='btn showModel'>
    </div>
    
    <div class='model' id='model' >
      <div class='model-dialog'>
        <h4>Model Heading</h4>
        <input type='button' value='X' class='close'>
        <hr>
        <p>
          Model Content Here...
        </p>
      </div>
    </div>
    
    <script>
      document.querySelector(".showModel").onclick=function(){
        document.querySelector("#model").style.display="block";
      }
      
      document.querySelector(".close").onclick=function(){
        document.querySelector("#model").style.display="none";
      }
    </script>
  </body>
</html>
Try it Yourself

Live Demo