Centering a div That Maintains Aspect-Ratio When There’s Body Margin

Avatar of Chris Coyier
Chris Coyier on

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

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 width/height and creating the margins from subtracting from those dimensions:

Amelia Wattenberger‘s idea is to set both height/width and max-height/max-width with viewport units, and center it with the classic translate trick:

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.