![How to Keep Aspect Ratio of Images in CSS](https://allma.si/blog/wp-content/uploads/2020/11/keep-aspect-ratio-in-css.png)
How to Keep Aspect Ratio of Images in CSS
If you ever wanted to resize an image disproportionately without losing aspect ratio in CSS β these two properties will help you out:
/* Center an image in itself without losing aspect ratio */
img {
width: 300px;
height: 300px;
object-fit: none;
object-position: 50% 50%;
background: blue;
}
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:
![](/assets/img/placeholder.png)
![](/assets/img/placeholder.png)
![](/assets/img/placeholder.png)
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:
![](/assets/img/placeholder.png)
![](/assets/img/placeholder.png)
![](/assets/img/placeholder.png)
The original size of the image is 100x100px, but they are set to 200x200 through CSS.
![How to keep image aspect ratio in CSS](https://allma.si/blog/wp-content/uploads/2020/11/keep-aspect-ratio-in-css.png)
![10 Best Practices for Quickly Improving Your CSS](https://miro.medium.com/max/700/1*m7oyUcMoJsW5wyzGfh6ydA.png)
Resources:
![Mentoring](/assets/img/mentoring.png)
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:
Courses
![CSS - The Complete Guide (including Flexbox, Grid and Sass)](https://img-c.udemycdn.com/course/480x270/1561458_7f3b_2.jpg)
CSS - The Complete Guide (including Flexbox, Grid and Sass)
![The HTML & CSS Bootcamp](https://img-c.udemycdn.com/course/480x270/5088684_a587_7.jpg)
The HTML & CSS Bootcamp
![The Creative HTML5 & CSS3 Course](https://img-c.udemycdn.com/course/480x270/3014898_c2e1_3.jpg)