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
Brian Hart used
vmin units for the aspect ratio sizing and centered it with flexbox:
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.
The post Centering a div That Maintains Aspect-Ratio When There’s Body Margin appeared first on CSS-Tricks.