Fit image inside div without stretching

Those images on the site you linked to are actual size, so the simple answer is just to resize the image.

You can't really do this without "stretching" the image if the image happens to be less than 300px wide or tall, but you can do it without changing the ratio, which is what I think you mean.

Here's the basic idea:

<div><img></div>

If you want to use 300px as a minimum width (you expect small images that need to be bigger), try this:

div {
    width:300px;
    height:300px;    
    overflow:hidden;
}
div img {
    min-width:100%;
}

Demo: http://jsfiddle.net/Z47JT/

If you want to clip images (because you expect them to be big) but not enlarge them, try this:

div {
    width:300px;
    height:300px;    
    overflow:hidden;
    position:relative;
}
div img {
    position:absolute;
}

Demo: http://jsfiddle.net/Z47JT/1/

Combine both these techniques if you want.

Another way is to simply use background-image on the container instead, but resizing it (if you want to stretch smaller images) will be difficult unless you use background-size which isn't fully supported. Otherwise, it's a great easy solution.


Use the flex box solution

Here is the html,

<div><img /></div>

Add styles

div{
   width:100%;
    height:250px;
    display:flex;
    justify-content:center;
    align-items:center;
    overflow:hidden
}
div img{
  flex-shrink:0;
    -webkit-flex-shrink: 0;
    max-width:70%;
    max-height:90%;
}

Tags:

Html

Css

Image