Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change modal's background color?

I was wondering how would I go around changing my modal’s background color after it has displayed, like the following: enter image description here I want the background color to cover the whole page and not just color the modal itself. I tried:

    .modal {
        background-color: rgb(255, 0, 0);
}

But this resulted as I said in the colored modal and not the whole page.
Here’s a snippet for refrence:

const modal = document.querySelector(".modal");
const openModal = document.querySelector(".open-button");
const closeModal = document.querySelector(".close-button");

openModal.addEventListener("click", () => {
  modal.showModal();
});

closeModal.addEventListener("click", () => {
  modal.close();
});
.modal {
    background-color: rgb(255, 0, 0);
}
<!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">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <button class="button open-button" >Open</button>

    <dialog class="modal">
        Hi! I'm 15Rabi
        <button class="button close-button" >Close</button>
    </dialog>
</body>
<script src="script.js"></script>

</html>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To change the backdrop color for a <dialog> element you needs to style the ::backdrop pseudo element like this:

.modal::backdrop {
  background-color: rgb(255, 0, 0);
}

Ideally though you’d want to to be a semi transparent color, not solid red, so you might want to use rgba instead

.modal::backdrop {
  background-color: rgba(255, 0, 0, 0.5);
}

Links to the relevant docs:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog
https://developer.mozilla.org/en-US/docs/Web/CSS/::backdrop

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading