Fit Image Within Different Aspect Ratio Using CSS

- 2 minutes read

Consider the following 800x400 image:

<img src="" alt="A randomly selected image">

Let’s imagine we wanted to place it within a 400x400 container.

The styling for our image might look like this:

img {
    height: 400px;
    width: 400px;

However, if a dimension of the image source is larger than the image container (in this case, the width is 400px larger), then the image will appear squished.

But if you wanted to fit the image within the container while preserving the original aspect ratio of the source, you add some CSS that uses the powerful object-fit property:

img {
    object-fit: contain;
    /* ... */

This will shrink our 800x400 image such that it takes up no more than 400px in either direction.

Link to this section Fitting an image without shrinkage

You can also fit an image within a container of different dimensions, without shrinking it.

By setting object-fit to cover, you can cut off the parts of the image that don’t fit, rather than compressing them or shrinking the entire image:

img {
    object-fit: cover;
    /* ... */

Link to this section Conclusion

These snippets work for other aspect ratios too. The 400x400 container is just an example.

Anyway, object-fit is an extremely powerful property that would have saved me hours of tedious experimentation if I knew about it earlier.

But I hope it at least saved you some time! Thanks for reading.