Responsive images with fixed aspect ratio using intrinsic sizing
Based on the now quite vintage A List Apart article from 2009, which looks at maintaining a video aspect ratio on resize, you can do the same for responsive images.
To achieve this we place our responsive image in a container element. By setting the padding-bottom
of this element to a percentage which matches the image's aspect ratio you'll ensure that it stays the same size.
To calculate this percentage just divide the natural width of your image by it's height and multiply by 100 to find the correct padding-bottom.
Example
Markup
<div class="image-wrapper">
<img class="responsive-image" src="/path/to/img.jpg" />
</div>
CSS
.image-wrapper {
position: relative;
padding-bottom: 20%;
}
.responsive-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Here we've set the padding bottom to 20%
to replicate a ratio of 1:5 - our image would be 5 times as wide as it is tall. We could use:
padding-top: 56.25%;
to apply a 16:9 ratio (9 / 16 = 0.5625).
Credits
Thanks to @ihart and Rich Hallows for passing on this technique.