How to Create Responsive Modal Images With CSS and JavaScript

Modal images are an essential element in web design that enhances user experience by allowing them to view images in full screen.

They are widely used to showcase products, portfolios, or detailed images.

This tutorial will guide you through the process of creating responsive modal images with CSS and JavaScript.


Step 1: HTML Markup

The first step is to create the HTML markup for the modal image. Here is an example of the HTML code:

<div class="img-container">
  <img src="image1.jpg" alt="image1">
  <button class="modal-btn">View Image</button>
</div>

Step 2: CSS Styles

The next step is to add CSS styles to the HTML elements. The CSS styles will control the positioning and appearance of the modal image.

Here is an example of the CSS code:

.img-container {
  position: relative;
  display: inline-block;
}

.modal-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #333;
  color: #fff;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
}

.modal-content {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  display: none;
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}

Step 3: JavaScript

The final step is to add JavaScript to open and close the modal image.

The JavaScript code will be used to control the behavior of the modal image. Here is an example of the JavaScript code:

var modalBtn = document.querySelector(".modal-btn");
var modalContent = document.querySelector(".modal-content");
var closeBtn = document.querySelector(".close-btn");

modalBtn.addEventListener("click", function() {
modalContent.style.display = "block";
});

closeBtn.addEventListener("click", function() {
modalContent.style.display = "none";
});

Conclusion

By following these simple steps, you can create a responsive modal image that will enhance the user experience of your website.

Modal images are a great way to showcase products, portfolios, or detailed images and make your website look more professional.

Don’t hesitate to experiment with different styles and animations to create a unique and visually appealing modal image.