Ask any question about CSS here... and get an instant response.
Post this Question & Answer:
How can I use CSS grid to create a responsive gallery with variable column sizes?
Asked on Feb 25, 2026
Answer
CSS Grid is an excellent tool for creating responsive galleries with variable column sizes. It allows you to define grid areas that adjust based on screen size, ensuring your gallery looks great on any device.
<!-- BEGIN COPY / PASTE -->
<style>
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 10px;
}
.gallery-item {
background-color: #ccc;
padding: 20px;
text-align: center;
}
</style>
<div class="gallery">
<div class="gallery-item">Item 1</div>
<div class="gallery-item">Item 2</div>
<div class="gallery-item">Item 3</div>
<div class="gallery-item">Item 4</div>
<div class="gallery-item">Item 5</div>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- The "grid-template-columns" property uses "repeat" with "auto-fill" to automatically create as many columns as will fit in the container, each with a minimum size of 150px and a flexible maximum size.
- The "gap" property adds space between the grid items, enhancing the visual separation.
- This setup ensures the gallery is responsive, adjusting the number of columns based on the container's width.
- Adjust the "minmax" values to change the minimum column size and flexibility.
Recommended Links:
