Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scale image to fit div

Tags:

css

I want to scale the picture to fit the main div class

http://jsfiddle.net/EyW99/

Sorry, forgot to mention that I need it to work in IE8

like image 366
Plexus81 Avatar asked Mar 22 '12 12:03

Plexus81


3 Answers

You can use the background-size:contain CSS property.

.image {
    background: url('http://astridterese.files.wordpress.com/2010/07/google.jpg') no-repeat;
    width: 100%;
    height: 100%;
    background-size: contain;
}

If you need to support old browsers (namely IE on Windows XP and below, since Vista and 7 users should be on IE9), use an <img> tag instead, as this causes the browser to scale the image to the dimensions you specify either in CSS height/width or the HTML attributes of the tag.

<img class="image" src="http://astridterese.files.wordpress.com/2010/07/google.jpg" />

like image 157
deed02392 Avatar answered Oct 22 '22 13:10

deed02392


Here is an update version of the fiddle that makes use of the CSS3 property background-size: http://jsfiddle.net/EyW99/2/

What you need to add to your styling is basically background-size: contain; to make the browser scale the image to the largest possible size of the image that still fits within your element, or background-size:X% X%; or background-size:Xpx Xpx; if you want to controll the sizing yourself.

Note

As background-size is a CSS3 property, it has limited browser support.

IE9+, Firefox 4+, Opera, Chrome, and Safari 5+.

Cross-browser soultion

This solution is maybe not as "nice" as the new CSS-property, but for cross-browser support you could change your div to an img, which will allow the browser to resize the image.

like image 39
Christofer Eliasson Avatar answered Oct 22 '22 12:10

Christofer Eliasson


.main{
    height: 113px;
    max-width: 400px;
}

.image {
    background: url('http://astridterese.files.wordpress.com/2010/07/google.jpg') no-repeat scroll 0 0 transparent;
    background-size: 100% 100%;
}

That works in Chrome but not IE8 so is probably useless.

Personally, I'd change the inner div to an image tag with it's width and height set to 100%. ​

like image 37
DoctorMick Avatar answered Oct 22 '22 13:10

DoctorMick