Blog>
Snippets

Modal with Overlay

Include a full-screen overlay behind the modal to focus attention and prevent interaction with the underlying page, handling clicks on the overlay to close the modal.
<!-- HTML structure for the Modal with Overlay -->
<div id="overlay" onclick="closeModal()" style="display: none;"></div>
<div id="myModal" class="modal" style="display: none;">
  <div class="modal-content">
    <span class="close" onclick="closeModal()">&times;</span>
    <p>Some text in the Modal..</p>
  </div>
</div>
This is the HTML markup for a modal with an overlay. It includes a full-screen overlay and a modal container with some content and a close button.
/* CSS for the Modal and Overlay */
#overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 1;
}

.modal {
  position: fixed;
  z-index: 2;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid #888;
  width: 80%;
  max-width: 600px;
  background-color: #fefefe;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
This CSS styles the overlay to cover the entire screen and the modal to be centered. The close button is also styled with hover effects.
// JavaScript functions to open and close the Modal
function openModal() {
  document.getElementById('overlay').style.display = 'block';
  document.getElementById('myModal').style.display = 'block';
}

function closeModal() {
  document.getElementById('overlay').style.display = 'none';
  document.getElementById('myModal').style.display = 'none';
}

// Example usage: openModal(); to open the modal
These JavaScript functions control the visibility of the overlay and the modal. The openModal function displays them, and the closeModal function hides them.