DEV Community

Cover image for The HTML 5 <Dialog /> Tag: The easiest way to create modal.
Francisco Inoque
Francisco Inoque

Posted on

The HTML 5 <Dialog /> Tag: The easiest way to create modal.

The HTML5 dialog tag is the easiest way to create a modal. All you need to do is add the tag to your page and you're done. You can then style the dialog with CSS and add behaviors to it with JavaScript.

What is dialog tag in html?

A dialog tag in HTML is used to create a pop-up dialog box on a web page.
The dialog tag defines a dialog box or window. This element can be used to display an alert message, a confirmation message, or anything that requires the user to respond.

Let's see some quick example

  • First let's create 3 files: index.html, main.js and style.css.

  • In index.html write this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Francisco Inoque">
    <title>The easiest way to do modal.</title>

    <link rel="stylesheet" href="style.css">
</head>
<body>

    <button class="btn-open" id="btn-open">Open modal</button>
   <dialog id="modal">
    <h1>Dialog Tag</h1>
    <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto voluptatibus accusantium enim provident distinctio fugiat, ex cumque pariatur consequatur repellat, aliquid voluptatem possimus. Inventore a quia consequatur fuga maxime exercitationem.
    </p>

    <button id="btn-close" class="btn-close">Close modal</button>
   </dialog>

   <script src="./main.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • In main.js write this code:
const btnOpen = document.querySelector("#btn-open");
const btnClose = document.querySelector("#btn-close")
const modal = document.querySelector("#modal");

btnOpen.onclick = () => {
  modal.showModal()
}


btnClose.onclick = () => {
    modal.close()
  }
Enter fullscreen mode Exit fullscreen mode
  • In style.css write this code:

dialog::backdrop {
    background-color: rgba(0 0 0 / .3);
}

dialog {
    width: 20%;
    border: none;
    border-radius: 14px;
    box-shadow: 0 0 0 .6em rgb( 0 0 0 / .3)
}

.btn-open {
    position:absolute;
    margin: 25% auto 0;
    left:45%;
    background-color: #8e2ddd;
    color: #fff;
    border: none;
    border-radius: 14px;
    padding: 1.5em;
    font-size: 18px;
    font-weight: bold;
    cursor: pointer
}

.btn-close {


    background-color: #ff0099;
    color: #fff;
    border: none;
    border-radius: 10px;
    padding: .8em;
    font-size: 13px;
    font-weight: bold;
    cursor: pointer
}
Enter fullscreen mode Exit fullscreen mode

So folks, that's all for today. Please like, comment and follow me.

Top comments (0)