๐จ Responsive Photo Gallery
Resize your browser window! The number of columns changes
automatically โ no media queries needed.
๐ผ
Eiffel Tower
Paris, France
๐ฒ
Forest Trail
Black Forest
๐ฏ
Ancient Temple
Kyoto, Japan
๐ฝ
Statue of Liberty
New York, USA
๐
Golden Hour
Santorini, Greece
๐ฐ
Neuschwanstein
Bavaria, Germany
.masonry {
display: grid;
grid-template-columns: repeat(auto-fit,
minmax(250px, 1fr));
gap: 20px;
}
๐ก The Magic Formula:
โข auto-fit = as many columns as fit, stretch to fill
space
โข minmax(250px, 1fr) = each column at least 250px,
can grow
โข No media queries needed! The browser handles
everything.
๐ง How It Works
/* When screen is 500px wide: */ /* 500 รท 250 = 2 columns โ each gets
250px */ /* When screen is 600px wide: */ /* 600 รท 250 = 2 columns โ
each gets 300px (extra space distributed) */ /* When screen is 750px
wide: */ /* 750 รท 250 = 3 columns โ each gets 250px */ /* When screen
is 1000px wide: */ /* 1000 รท 250 = 4 columns โ each gets 250px */ /*
When screen is 1200px wide: */ /* 1200 รท 250 = 4 columns โ each gets
300px */
๐ auto-fit vs auto-fill
auto-fit collapses empty columns (items stretch).
auto-fill keeps empty columns (reserves space).
/* auto-fit - columns stretch to fill space */
.grid { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
/* auto-fill - reserves space for empty columns */
.grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
๐ For photo galleries, use auto-fit โ you want
images to fill the available space without gaps.
๐ Quick Reference
/* =================================== THE MAGIC RESPONSIVE GRID
FORMULA =================================== */ .responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit,
minmax(250px, 1fr));
gap: 20px;
}
/* =================================== VARIATIONS
=================================== */ /* For smaller cards (like
avatars) */
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
/* For larger cards (like product displays) */
grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
/* With max-width constraint on items */
.card { max-width: 400px; margin: 0 auto; }
๐ง Quick Quiz
/* Question 1: What does auto-fit do? */ /* Answer: Collapses empty
columns, makes items stretch to fill space */ /* Question 2: What does
minmax(250px, 1fr) mean? */ /* Answer: Minimum 250px wide, maximum 1
fraction of available space */ /* Question 3: Do you need media
queries with auto-fit + minmax? */ /* Answer: No! The grid
automatically adjusts */ /* Question 4: What's the difference between
auto-fit and auto-fill? */ /* Answer: auto-fit collapses empty
columns, auto-fill reserves space for them */