I've the following image
<div class="product-main-img">
<img src="@Model.ImageUrl" alt="@Model.Name" />
</div>
This image could be bigger than its container or smaller than it. When smaller I need to center it vertically and horizontally but if it's bigger, I need to contain it and center the shorter side.
I can do this, each on its own, and see which styling I need to apply using JavaScript; but I kind of want to solve it using pure CSS. Any idea?
This assumes the container has specified dimensions ( since you mention that the img
might be bigger/smaller ).
So use flex for the container ( which allows centering its child element ) add min-width
and max-height
to the image.
.product-main-img { width: 300px; height: 150px; border:1px solid black; display:flex; flex-direction:column; align-items:center; justify-content:center; } .product-main-img img { max-width: 100%; max-height: 100%; }
<div class="product-main-img"> <img src="http://dummyimage.com/400x100" alt="@Model.Name" /> </div> <div class="product-main-img"> <img src="http://dummyimage.com/100x200" alt="@Model.Name" /> </div> <div class="product-main-img"> <img src="http://dummyimage.com/200x100" alt="@Model.Name" /> </div> <div class="product-main-img"> <img src="http://dummyimage.com/400x200" alt="@Model.Name" /> </div>
One easy way of doing this is to set the image as the background-image
of the <div>
, then use background-position: center
and background-size: contain
to make it fit to the container. For example:
.image-container { border: 2px solid black; width: 100px; height: 100px; background-position: center; background-repeat: no-repeat; background-size: contain; }
<div class="image-container" style="background-image: url(https://lorempixel.com/400/200/cats/1/)" ></div> <br> <div class="image-container" style="background-image: url(https://lorempixel.com/200/400/cats/1/)" ></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.