Reputation: 1320
I am accessing an API with different product images. These images are not always the same dimensions unfortunately. I want to display them in a 250x250 div.
So sometimes the image is portrait and the image should be scaled on based on the height (not filling the full 250px width). Sometimes it is landscape and it should be scaled to the width (not filling the full 250px) height.
Honestly I have no clue how to do this (with CSS - if possible at all) so any help is appreciated.
Thanks.
edit it was mentioned in the comments that it duplicates question: Scale image with css to both width and height to scale there is overlap indeed - however i did not find the answers at this question satisfying enough (for my understanding).
Upvotes: 0
Views: 1030
Reputation: 16438
Use the other answer for backgound image, documentation is here for what contain
does https://developer.mozilla.org/en-US/docs/Web/CSS/background-size
If you have to use an image and cannot use background image or you want the image tags in the html for better SEO then use the below. By setting both max width and height to 250px, it automatically sizes the image correctly. It will stop sizing once either one of the dimensions reaches 250
.test1 {background: blue;}
.test2 {background: green;}
.test2 img,
.test1 img{
max-width: 250px;
max-height: 250px;
}
.test1,
.test2 {
text-align: center;
width: 250px;
height: 250px;
}
<div class="test1">
<img src="https://wallpaperbrowse.com/media/images/_89716241_thinkstockphotos-523060154.jpg" />
</div>
<div class="test2">
<img src="http://images2.fanpop.com/image/photos/10200000/Some-Random-Stuff-wumbo-10274290-300-498.jpg" />
</div>
Upvotes: 0
Reputation: 1572
As Georgy Malanichev pointed, background is a nice option, if you also need the images for being indexed to get better SEO, you can set it with max-height and max-width CSS property:
div.imgContainer{
float: left;
width: 250px;
height: 250px;
border: 1px solid black;
}
div.imgContainer > img {
max-width: 250px;
max-height: 250px;
}
<div class="imgContainer">
<img src="http://joelbonetr.com/images/fwhee.png">
</div>
<div class="imgContainer">
<img src="http://joelbonetr.com/images/root.jpg">
</div>
<div class="imgContainer">
<img src="https://lh3.googleusercontent.com/bx2KTx4kmESKvwL2Npc8tdLuhIWFj3_ewMkAHNI6_5vj1tOrAukZD794wJqWRb_H_8I=w250-h250">
</div>
<div class="imgContainer">
<img src="https://www.venca.es/i/967184/l/top-sexy-de-muselina-elastica-flocada-en-terciopelo-con-tiras-elasticas-negro-burdeos.jpg">
</div>
As you can see if you inspect, all divs are 250x250 px, and the images fit in resizing when needed.
Upvotes: 0
Reputation: 336
Sounds like you want to be applying images using background-image
and giving them background-size: contain
:
.product-img {
width: 250px;
height: 250px;
background-image: url(path/to/image);
background-size: contain;
}
Upvotes: 3