CSS Tip - Maintaining Aspect Ratio

This quick and easy CSS trick comes in handy when you want to make sure that an image or box always maintains a specific aspect ratio. 

Mat French
January 6, 2021

A good example of where I use this a lot is for a blog featured image on client websites - we usually want to ensure that the layout remains the same even if an image of a different size is used.

Put as simply as possible, padding-top and padding-bottom are based on an element’s width, not the height as you might expect. So all we do is set the padding-top or padding-bottom to be the % of the width we want to maintain, set the height to 0 so that the padding is all that affects the height of the element, and then set the image as a background image so it doesn’t get squished.

Step-by-step breakdown:

In this example I want to maintain the ratio of 1200px by 630px (a size that’s often used for meta images). I’ll be using a div element to hold the image.

  1. Divide the short side by the long side to get the fraction you need for the ratio (e.g 630 / 1200 = 0.525)
  2. Multiple that by 100 to get the percentage value you need (52.5%)
  3. Set the div height to 0
  4. Set the padding-top or padding-bottom to the percentage value
  5. Set the background of the div to the image
  6. Usually set the background-size to cover and background-position to center

And that’s it, your box will now always maintain the correct ratio, even when a different size image is used - which can happen a lot for example if a client has no access to image editing software, or simply doesn’t want to have to resize images.

Quick list for other ratios:

Use these ratios as the padding-top or bottom. Don’t forget to set the height to 0.

  • Square (1:1) = 100%

Common landscape ratios:

  • Widescreen (16:9) = 56.25%
  • Social Meta (120:63) = 52.5%
  • 5:4 landscape = 80%
  • A4 landscape = 70.7%

Common Portrait Ratios:

  • Widescreen Portrait (9:16) = 177.78%
  • A4 portrait = 141.43%
  • 4:5 portrait = 125%


We hope you enjoyed the article

Like what you read and fancy a chat? Do it here or go ahead and follow us on social:

Meet the author:

Mat French

Creative Director

Began playing around in Photoshop that came with my first PC at age 8, and never stopped. My first paid design work was a logo for a local manufacturing business in primary school at age 10 - I was paid in sweets and food, and a tour around the factory. I've been fortunate enough to work in agencies and small businesses as in-house designers, freelance on and off since university, before starting Oddbox Studio, and now more recently - Plato Agency. When I'm not building websites or designing or writing, I'm usually reading something about one of those things. It's safe to say design is a lifelong passion.