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.
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.
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.
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.
Use these ratios as the padding-top or bottom. Don’t forget to set the height to 0.
Common landscape ratios:
Common Portrait Ratios:
Like what you read and fancy a chat? Do it here or go ahead and follow us on social: