Project Structure
photo-gallery/
├── index.html
├── styles.css
└── script.js
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Photo Gallery</title>
</head>
<body>
<div class="gallery">
<div class="gallery-item">
<img src="https://via.placeholder.com/300" alt="Photo 1">
</div>
<div class="gallery-item">
<img src="https://via.placeholder.com/300" alt="Photo 2">
</div>
<div class="gallery-item">
<img src="https://via.placeholder.com/300" alt="Photo 3">
</div>
<div class="gallery-item">
<img src="https://via.placeholder.com/300" alt="Photo 4">
</div>
<div class="gallery-item">
<img src="https://via.placeholder.com/300" alt="Photo 5">
</div>
<div class="gallery-item">
<img src="https://via.placeholder.com/300" alt="Photo 6">
</div>
</div>
<div class="modal" id="modal">
<span class="close" id="close">×</span>
<img class="modal-content" id="modal-img">
</div>
<script src="script.js"></script>
</body>
</html>
2. styles.css
cssCopy codebody {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.gallery {
display: flex;
flex-wrap: wrap;
gap: 10px;
padding: 20px;
}
.gallery-item {
flex: 1 1 calc(33.333% - 10px);
cursor: pointer;
}
.gallery-item img {
width: 100%;
border-radius: 8px;
transition: transform 0.3s;
}
.gallery-item img:hover {
transform: scale(1.05);
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.8);
}
.modal-content {
margin: auto;
display: block;
max-width: 80%;
}
.close {
position: absolute;
top: 20px;
right: 30px;
color: white;
font-size: 40px;
font-weight: bold;
cursor: pointer;
}
3. script.js
javascriptCopy codeconst galleryItems = document.querySelectorAll('.gallery-item img');
const modal = document.getElementById('modal');
const modalImg = document.getElementById('modal-img');
const closeModal = document.getElementById('close');
galleryItems.forEach(item => {
item.addEventListener('click', () => {
modal.style.display = 'block';
modalImg.src = item.src;
});
});
closeModal.addEventListener('click', () => {
modal.style.display = 'none';
});
window.addEventListener('click', (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
Instructions
- Create the Project Structure: Make a new directory and create the three files listed above.
- Copy the Code: Copy the respective code into each file.
- Open
index.html
: Open this file in a web browser to view your photo gallery.
Leave a Reply