I plan to design a grid system with 3 cells in each row, each cell contains an image.
I prefer to style each image with rounded corner and object-fit:contain
, the image should stay within the parental div
container and still appears to be in the right aspect ratio with decorative round-corners,
Initially I tried to use width to be 100% and height to be 300px to size the img
tag, it won't work properly, (check out the 2nd part of the article for an alternative solution.) The rounded corners only show up in some special screen sizes, the scale of the image will be off too when the screen is too large.
I later found out the right solution (1st) should be to use max-height and max-width of both 100%. This way the image will be contained inside its parental div
container neatly with rounded corners for all screen sizes, meantime the image can preserve the correct aspect ratio as well.
If the image width needs to be fixed, the height can be auto for preserving the right aspect ratio for an image.
Check out this snippet for html:
<div class="image">
<img src="https://tinyurl.com/3t3fvdje" alt="">
</div>
The CSS should be like this:
.image {
width: 500px;
height: 300px;
}
img {
max-width: 100%;
max-height: 100%;
border-radius: 15px;
object-fit: contain;
}
To see the code pen, click the result button:
See the Pen
resize image in a div by Susan G (@Koo8)
on CodePen.
What if I use 'cover' instead of 'contain'?
For the above example, the object-fit:contain;
is used. In order to have all images neatly fit into the 3-columns grid system, and also with each image to have the same height, this first solution turns out to be not good enough. Because it requires to pre-resize all original images to be the same size before any uses. Problems will occur when if one image is in portrait layout and others are in landscape layout, the display of images with different heights looks like a mess for my project.
So here comes the second solution, to use object-fit:cover;
instead. Now I can use 'width' and 'height' with its specific values, such as I mentioned at the beginning of this article, with width to be 100% and height to be 300px exact. After all the changes, the rounded corners stay there for all sizes of screens, the images appears the same size with right aspect ratios, the whole design looks neat and aesthetic.
img {
width: 100%;
height: 300px;
border-radius: 15px;
object-fit: cover;
}
The image nicely stretches across the whole
div
container with a fixed height of 300px.