View Single Post
noleli2
Senior Member
 
Join Date: May 2004
Location: Chicago
 
2022-09-12, 17:55

I’m super late to this (I’m not as active here as I used to be), but the beauty of `grid` is that it can do automatic layouts without needing to resort to media queries.

By saying you want a single column up to 600px, you’re essentially saying that you’re ok with a minimum photo width of 300px, because that’s what it’ll be once there are 2 columns. So the magic line is

Code:
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
This will create as many columns as necessary to keep the photo at least 300px wide, but can’t be wider than all of the remaining grid container space. (The difference between `auto-fit` and `auto-fill` is subtle, but in this case it doesn’t matter.)

Because you also didn’t want more than 3 columns, I set a `max-width` on the grid container.

Full example:

Code:
<!DOCTYPE html> <html> <style> body { font-family: sans-serif; } .container { --min-photo-width: 300px; --max-columns: 3; --gap: 16px; display: grid; gap: var(--gap); margin-inline: auto; /* this will create as many columns as necessary to keep the photo at least 300px, and up to all of the remaining grid container space */ grid-template-columns: repeat(auto-fit, minmax(var(--min-photo-width), 1fr)); /* to limit it to 3 columns, want to cap the container size as 1px less than what would allow 4 columns */ max-width: calc(var(--min-photo-width) * (1 + var(--max-columns)) + var(--gap) * var(--max-columns) - 1px); } .image-placeholder { background-color: lightgray; aspect-ratio: 1; border-radius: 16px; display: grid; place-content: center; font-size: 3rem; } </style> <body> <!-- Header --> <div class="header"> <h1>Camera Snapshot Grid</h1> </div> <!-- Photo Grid --> <div class="container"> <div class="image-placeholder">1</div> <div class="image-placeholder">2</div> <div class="image-placeholder">3</div> <div class="image-placeholder">4</div> <div class="image-placeholder">5</div> <div class="image-placeholder">6</div> <div class="image-placeholder">7</div> <div class="image-placeholder">8</div> <div class="image-placeholder">9</div> </div> </body> </html>
  quote