CSS AdvancedLesson #149

CSS Image Modal

A modal image gives a user the ability to display a larger version of an

Responsive Modal Image Gallery

A modal image gives a user the ability to display a larger version of an image, without navigating away from the current page. When a user clicks on a modal image, it shows a popup window that appears on top of the main content of the webpage, often with a semi-transparent background. The modal must be closed by the user, typically with a "close" button or an "X" sign in top-right corner.

This example demonstrates how to use HTML, CSS and JavaScript together, to create a responsive modal image gallery.

We use CSS to create a modal window (dialog box), and hide it by default.

Then, we use a JavaScript to show the modal window with the correct image inside, when a user clicks on the image:

<img src="img_5terre.jpg" alt="Cinque Terre" class="gallery-item" onclick="openModal('modal1', 'Cinque Terre')" width="600" height="400"> <img src="img_forest.jpg" alt="Forest" class="gallery-item" onclick="openModal('modal2', 'Forest')" width="600" height="400"> <img src="img_lights.jpg" alt="Northern Lights" class="gallery-item" onclick="openModal('modal3', 'Nothern Lights')" width="600" height="400"> <img src="img_mountains.jpg" alt="Mountains" class="gallery-item" onclick="openModal('modal4', 'Mountains')" width="600" height="400">

× <img src="img_5terre.jpg" alt="Cinque Terre" class="modal-content" width="600" height="400">

× <img src="img_forest.jpg" alt="Forest" class="modal-content" width="600" height="400">

× <img src="img_lights.jpg" alt="Northern Lights" class="modal-content" width="600" height="400">

× <img src="img_mountains.jpg" alt="Mountains" class="modal-content" width="600" height="400">

Example

Example Code

html
Try it Yourself
Live Output Preview:


Interactive Code Examples

CSS Example 1

html
Try it Yourself
Interactive runnable CSS example from EA Academy.
Live Output Preview: