Plexus81
Plexus81

Reputation: 1251

Scale image to fit div

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

Upvotes: 7

Views: 15972

Answers (4)

Christofer Eliasson
Christofer Eliasson

Reputation: 33875

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.

Upvotes: 2

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

If you don't need a pure CSS solution, you can use JavaScript for a solution that works on all major browsers. The bgStretcher plugin for jQuery will do what you want and will adjust the size dynamically if the size of the div changes.

Upvotes: 0

deed02392
deed02392

Reputation: 5032

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" />

Upvotes: 13

DoctorMick
DoctorMick

Reputation: 6793

.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%. ​

Upvotes: 1

Related Questions