Is there a way to use max-width and height for a background image?

technopeasant picture technopeasant · Jun 10, 2011 · Viewed 147k times · Source

That simple.

Moving my layout into a fluid territory, working on scalable images. Using the img tag and setting max-width to 100% works perfectly, but i'd rather use a div with the image set as its background.

The issue I'm running into is that the image doesn't scale to the size of the div it's in the background of. Any way to add markup to the background code to set it to 100% width of it's container?

#one {
    background: url('../img/blahblah.jpg') no-repeat;
    max-width: 100%;
}

Answer

Dan picture Dan · Jun 10, 2011

As thirtydot said, you can use the CSS3 background-size syntax:

For example:

-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;

However, as also stated by thirtydot, this does not work in IE6, 7 and 8.

See the following links for more information about background-size: http://www.w3.org/TR/css3-background/#the-background-size