Ask any question about CSS here... and get an instant response.
Post this Question & Answer:
How can I create a responsive image gallery using CSS Grid?
Asked on Mar 12, 2026
Answer
Creating a responsive image gallery with CSS Grid is efficient and straightforward. You can define a grid layout that automatically adjusts the number of columns based on the screen size.
<!-- BEGIN COPY / PASTE -->
<style>
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 10px;
}
.gallery img {
width: 100%;
height: auto;
display: block;
}
</style>
<div class="gallery">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<!-- Add more images as needed -->
</div>
<!-- END COPY / PASTE -->Additional Comment:
- The "grid-template-columns" property uses "auto-fill" to automatically create as many columns as fit in the container, with each column being at least 150px wide.
- The "gap" property defines the spacing between grid items, ensuring a consistent look.
- Images are set to "width: 100%" to ensure they fill their grid cell, maintaining aspect ratio with "height: auto".
- This setup is responsive and will adjust the number of columns based on the container's width.
Recommended Links:
