When creating responsive websites, sometimes it’s important to keep elements the same aspect ratio regardless of width. This is extra important for images that have a focal point like faces or a product to make sure the important parts of the image area always visible.
This handy tool can calculate a target element’s width and height based on a source width and height and also shows a method using :after to create a responsive element with CSS.
How it’s Calculated
With some basic math, we can get both the target width and height and value for padding-bottom based on the source width/height and the target width or height.
aspectRatio = (sourceWidth / sourceHeight);
Then we can get the adjusted width or adjusted height, depending on which value we know.
adjustedWidth = targetHeight * (sourceWidth / sourceHeight); adjustedHeight = targetWidth * (sourceHeight / sourceWidth);
Getting the value for the responsive CSS padding-bottom value is as easy as:
paddingBottom = sourceHeight / (sourceWidth / 100);
… or, you can just let this tool do the math for you 😉