Andrew Welch had a little CSS challenge the other day to make an ordinary div:
• centered vertically + horizontally
• scales to fit the viewport w/ a margin around it
• maintains an arbitrary aspect ratio
• No JS
There’s a video in that tweet if it helps you visualize the challenge. I saw Paul Bakaus blogging about this the other day, too, so it’s a thing that comes up!
Mark Huot got fancy applying aspect ratios directly with
height and creating the margins from subtracting from those dimensions:
Amelia Wattenberger‘s idea is to set both
max-width with viewport units, and center it with the classic
Eric A. Meyer did the same, only centered with flexbox instead.
Brian Hart used
vmin units for the aspect ratio sizing and centered it with flexbox:
Benoît Rouleau did the same but used
calc() for the margins in a different unit.
Andrew really likes Jonathan Melville’s approach. Most of it is in Tailwind classes so it’s a smidge hard for me to understand as I’m not used to looking at code like that yet.
Andrew said he ultimately went with the
vmin thing — although I see he’s using
calc() to subtract
vmin units from each other which isn’t really necessary unless, I guess, you wanna see the math.
I like the solution that uses width/height along with opposing max-width/max-height — that solution is probably the best option for compatibility with older browsers. But since this is pretty much exactly what the vmin unit is for, I would say that’s probably the best solution.