Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit image inside div without stretching

Tags:

html

css

image

I need to fit an image inside a 300x300 div without stretching the image. I've seen this on the huff post, the slider on this page :

http://www.huffingtonpost.com/2012/01/07/katy-perry-divorce_n_1191806.html

The images are clipped but not stretched. Instead of using max-width, max-height.

How do I do this?

like image 376
Jack Stewart Avatar asked Jan 08 '12 03:01

Jack Stewart


2 Answers

simple way to do this....

.div {
background-image: url(../images/your-image.png);
background-size:cover;
background-position:center;
background-repeat:no-repeat;

}

like image 173
Optimaz ID Avatar answered Oct 07 '22 00:10

Optimaz ID


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.

like image 20
Wesley Murch Avatar answered Oct 07 '22 01:10

Wesley Murch