Fitting and center aligning images both vertically and horizontally (with and without cropping) in container through pure CSS

With cropping using img tag:

.image-box {
width: 300px;
height: 200px;
background-color: turquoise;

}
.image-box img {
width: 100%;
height: 100%;
-o-object-fit: cover;
object-fit: cover;
}
<div class="image-box">
<img src="image.png">
</div>

This always fits the image into the container. It will feel like the image has been “zoomed in”. The downside is if your image is way too smaller than the container it will look pixelated when zoomed in.

PS: Fails on IE :(

Here’s the pen:

Without cropping using img tag:

.image-box {
width: 300px;
height: 200px;
background-color: turquoise;
display: flex;
align-items: center;
justify-content: center;
}
.image-box img {
max-width: 100%;
max-height: 100%;
}
<div class="image-box">
<img src="image.png">
</div>

Here the small image problem doesn’t occur. You can use either of these two approaches if SEO is your concern since the img src link will be crawled.

You can play with the code in this pen. Change the url of the image to test for different image dimensions.

If SEO is not you concern you can use the background-image property as explained next.

With cropping:

.image-box {
width: 300px;
height: 200px;
background-color: turquoise;
background-position: center center;
background-size: cover;
background-repeat: no-repeat;
background-image: url(image.png);
}
<div class="image-box">
</div>

Without cropping:

Just change the background-size rule to contain and you’re good to go.

background-size: contain;

Let me know in the comments what you think :)