How do I adjust the size of my image inside a container while maintaining its position and aspect rat

26 Views Asked by At

I am building a website that displays NBA players. To do this, I am creating a div called "player-holder" and putting an image called "player-image" inside, so that it displays, essentially a portrait of my player.

My CSS code looks like this:

#player-image {
   object-fit: cover;
   width: 100%;
   height: 100%; 
}

#player-holder {
   border: 2px solid black;
   width: 100px;
   height: 100px;
}

Currently, my player image appears at the bottom of the player holder, which is good. However, my problem is that the image is bigger than what I would like it to be. How do I adjust the size of the player-image so that it stays at the bottom of the holder while maintaining its aspect ratio?

I tried switching it to object-fit: contain, but this leaves space between the bottom of the player holder and the image, which doesn't work for the purposes of my website. I also tried using a flex display with vertical columns, but this didn't seem to work either. Editing the width and height, just crop the image instead of shrinking it.

1

There are 1 best solutions below

0
Geoduck On

using object-position along with object-fit as shown in the example.

div {
width: 20px;
height: 100px;
background-color: gray;
margin: auto;
}

img {
object-fit: contain;
object-position: bottom center;
width: 100%;
height: 100%;
}
<div>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAABHNCSVQICAgIfAhkiAAAAfBJREFUKJE1kktrE1EcR3937rySaR4kbanpy7pQNEFFycaFtJsKuhDXSjELF134Cbr0O2RbEKJfwKViEBSEZtUEKipUxajVNo+ZTGbu439dWM/6nN1hOOXhWfi1hWB7KefcL/tOrZRx8XGouss565k49pob7cMEADgAPN8sLVfngtezWW8rNbwiLcdemc/bR1OqrBT8Wypr7k6m6YvuQI3Z7jp83y68z7n25YLnoOi7mJnJ4ElniMaNNSgy+PD1Ny7YcRdDv87vreUfM8a2+rHBl0ijH2v8khYebV7E0/0/KJeK2FgKQFE0P6TJCdu5FuxlbH69VvawkLXh2Rye6+DtmKN+aRHvvsdYNFOI0RiD8aRjnyvY1TNZBy5nkGTANOHV5xFurubhTUJUkjESoXClyNFnTtXK2YwJIkgiCE14+S1Gfd4F1xJ7B33UsoQyU/h0HCPVilmSTE/qf/KbHwmuzjoADFKlEQuFaCow5wIHgxSjRPYsRdQSZNA5Ejhf4GAgpJqQaEKqNSKhEEoFzoDUUMsiEzYPBnJ/NgO4lkF6Kv6cKAQ2EEqFSChwRj3SYdNqtJEsBOZOwWHdROvTgHAYSuQcQiQUIql6RZ/fbrSRsP9r7K7DZyzYthh7MBKoniSE1bzVY4y1SIfNRhsJAPwFZmj6yN9EOrsAAAAASUVORK5CYII=">
</div>