Nero296
Nero296

Reputation: 85

How to upscale an Img in CSS while, maintaining the aspect ratio?

After googling around a bit, I found this

HTML

<div class="divContainer">
    <img src="image.png">
<div>

CSS

.divContainer{
   width :200px;
   height:200px;
   border:solid;
 }

img{
    width: 100%;
    height: 100%;
    object-fit: contain;
}

This works well but it can only scale until it reaches the native resolution of the original picture and stops scaling with the div container but, I want it to go ahead and upscale beyond its native resolution.

Any ideas?

Upvotes: 5

Views: 4325

Answers (2)

N&#39;Bayramberdiyev
N&#39;Bayramberdiyev

Reputation: 3620

Change object-fit: contain; to object-fit: cover;.

.divContainer {
    width: 700px; /* Bigger than image's width. */
    height: 500px; /* Bigger than image's height. */
    border: solid;
}

img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
<div class="divContainer">
    <img src="https://dotjpg.co/YfUB.jpg"> <!-- Image Dimensions: 640px x 426px -->
<div>

Upvotes: 4

billk
billk

Reputation: 71

First off, you should use auto for the height if you want to keep the aspect ratio. Just set the width. Second, in your example because you set a height and width on the parent element, that's as much as the img can "grow." It's not stopping because of it's native size, but because of its parent's size.

Upvotes: 0

Related Questions