Resize an image without compressing it in CSS
You know what it is... That famous profile picture you want to display for your user with rounded corners, which is becoming a hassle due to the original photo's dimensions... Fortunately, thanks to CSS, it's very simple to resize an image without compressing it. Let's go through it together!
The Problem with Images
When we want to display an image, we must not forget that its original size can quickly become annoying: in portrait or landscape mode, when we want to display it in a square form, or even just resize it, it can quickly become difficult to handle in the long run...
A Small Example
Here is an example representing a profile picture that becomes very compressed:
<p>Your profile picture</p>
<img src="https://image.freepik.com/free-photo/asian-women-traditional-japanese-kimonos-fushimi-inari-shrine-kyoto-japan_335224-245.jpg" alt="Japan" />
p {
font-weight: bold;
font-family: arial;
font-size: 1.5rem;
}
img {
width: 300px;
height: 300px;
border-radius: 50%;
}
The problem with this example is that the profile photo is reduced in width, and the image becomes very compressed to fit into the dimensions we specified with the CSS of the img
tag:
width: 300px
height: 300px
The Miracle Solution
Fortunately, CSS allows us to resize an image without distorting its display, all thanks to the object-fit
property.
This handy property can take all of these values:
fill
- The image must respect the given dimensions, even if it gets distorted;contain
- The image must be contained within the given dimensions while maintaining its original ratio;cover
- The image must cover the given dimensions and adjust to leave no white space;none
- The image must respect the dimensions, but it is not resized: the original size is kept, and the image is simply cropped when it exceeds the specified width and height;scale-down
- This is almost likecontain
andnone
, except that this value chooses the smallest final rendered size (which means that ifcontain
allows the image to be smaller thannone
,scale-down
will choose to display the image as if you specifiedcontain
).
In all these possibilities, you guessed it... We need cover
!
Its functionality is identical to the background-size: cover
property you may have used before. The image will be represented to leave no gaps without being distorted.
So, we have the following code to make our example work perfectly:
p {
font-weight: bold;
font-family: arial;
font-size: 1.5rem;
}
img {
width: 300px;
height: 300px;
border-radius: 50%;
object-fit: cover;
}
By simply adding the object-fit: cover
property to all your images, you can resize them without compressing them. All that's left is for you to have fun with this property!
If you want to learn more, especially about HTML and CSS, we have a complete training dedicated to these two languages. Don't forget to share this article with your friends if you think they might need it—you'd be doing them a great service for their images!