How to create: Modal image
- Previous Page Slide Gallery
- Next Page Lightbox
Learn how to use CSS and JavaScript to create responsive modal images.
×
Modal image
Modal is a dialog/popup window displayed at the top of the current page.
This example uses most of the code from the previous example "Modal Box", but in this example, we use an image.
Step 1 - Add HTML:
<!-- Trigger modal box --> <img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px"> <!-- Modal box --> <div id="myModal" class="modal"> <!-- Close button --> <span class="close">×</span> <!-- Modal content (image) --> <img class="modal-content" id="img01"> <!-- Modal title (image text) --> <div id="caption"></div> </div>
Step 2 - Add CSS:
/* Set the style for the image that triggers the modal */ #myImg { border-radius: 5px; cursor: pointer; transition: 0.3s; } #myImg:hover {opacity: 0.7;} /* The Modal (background) */ .modal { display: none; /* Default is hidden */ position: fixed; /* Stay in place */ z-index: 1; /* Stay on top */ padding-top: 100px; /* Position of the frame */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ overflow: auto; /* Enable scrolling if needed */ background-color: rgb(0,0,0); /* Fallback color */ background-color: rgba(0,0,0,0.9); /* Black with transparency */ } /* Modal Content (Image) */ .modal-content { margin: auto; display: block; width: 80%; max-width: 700px; } /* Title of modal image (image text) - Same width as the image */ #caption { margin: auto; display: block; width: 80%; max-width: 700px; text-align: center; color: #ccc; padding: 10px 0; height: 150px; } /* Add animation - Zoom in the modal */ .modal-content, #caption { animation-name: zoom; animation-duration: 0.6s; } @keyframes zoom { from {transform:scale(0)} to {transform:scale(1)} } /* Close button */ .close { position: absolute; top: 15px; right: 35px; color: #f1f1f1; font-size: 40px; font-weight: bold; transition: 0.3s; } .close:hover, .close:focus { color: #bbb; text-decoration: none; cursor: pointer; } /* Image width is 100% on small screens */ @media only screen and (max-width: 700px){ .modal-content { width: 100%; } }
Step 3 - Add JavaScript:
// Get the modal var modal = document.getElementById("myModal"); // Get the image and insert it into the modal - use its "alt" text as the title var img = document.getElementById("myImg"); var modalImg = document.getElementById("img01"); var captionText = document.getElementById("caption"); img.onclick = function(){ modal.style.display = "block"; modalImg.src = this.src; captionText.innerHTML = this.alt; } // Get the <span> element to close the modal box var span = document.getElementsByClassName("close")[0]; // When the user clicks on the <span> (x), close the modal box span.onclick = function() { modal.style.display = "none"; }
Related Pages
Tutorial:How to Create Modal
Tutorial:How to Create Modal Gallery
- Previous Page Slide Gallery
- Next Page Lightbox