πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Keep Aspect Ratio of Images in CSS

How to Keep Aspect Ratio of Images in CSS

Ferenc Almasi β€’ 2020 November 18 β€’ Read time 1 min read
  • twitter
  • facebook
CSS

If you ever wanted to resize an image disproportionately without losing aspect ratio in CSS β€” these two properties will help you out:

Copied to clipboard! Playground
/* Center an image in itself without losing aspect ratio */
img {
    width: 300px;
    height: 300px;
    object-fit: none;
    object-position: 50% 50%;
    background: blue;
}
aspect-ratio.css

It uses object-fit with object-position. By default, object-fit takes the value of fill, which scales the image disproportionately if the container doesn't match the aspect ratio of the image. object-position on the other hand, sets the position of the image inside the container. To better understand how they work, take a look at object-fit taking up different values:

object-fit: fill; (default)
object-fit: contain;
object-fit: none;

The original size of the images is 200x300, but they are set to 200x200 through CSS.

With object-fit set to none on every image, observe how object-position changes the position of the image inside itself:

object-position: left top;
object-position: 50% 50%; (dead-center)
object-position: right bottom;

The original size of the image is 100x100px, but they are set to 200x200 through CSS.

How to keep image aspect ratio in CSS
If you would like to see more Webtips, follow @flowforfrank

10 Best Practices for Quickly Improving Your CSS

Resources:

  • twitter
  • facebook
CSS
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.