CSS Challenge: Centering a Div With Aspect Ratio and Body Margin
Andrew Welch recently posed a small CSS challenge: take an ordinary div and make it centered vertically and horizontally, scale it to fit the viewport while keeping a margin around it, hold an arbitrary aspect ratio, and do it all without JavaScript. The tweet includes a video to help visualize the problem, and Paul Bakaus also blogged about the same challenge, so it's clearly a recurring issue.
Several developers offered solutions. Mark Huot applied aspect ratios directly using width/height and created margins by subtracting from those dimensions. Amelia Wattenberger set both height/width and max-height/max-width with viewport units, centering using the classic translate trick. Eric A. Meyer did the same but centered with flexbox instead.
Brian Hart used vmin units for the aspect-ratio sizing and centered with flexbox. Benoît Rouleau also used flexbox but calculated the margins with calc() in a different unit.
Andrew favored Jonathan Melville's approach, most of which is in Tailwind classes. In the end, Andrew went with the vmin solution, though he's using calc() to subtract vmin units from each other, which isn't strictly necessary unless you want to see the math.



