Setting a responsive background image

Making images contained within the HTML responsive is easy as we saw with our responsive images… but what about background images applied within the CSS.  

We could use the experimental background-size property with the key advantage in being able to detect its own centre (using background-position:centre centre) and does quite well in most scenarios.

However, it still breaks when a containing element become very narrow.

The reason for this is that width:100% is given priority. You could change it to height:100%, but then it would break atwider sizes instead. You could give both width and height a value of 100%, but then you’d lose proportion as the image fails to maintain its correct ratio. And the really key thing here is that you’d need to know your preference in advance, which just won’t work for dynamic content: add more text and suddenly your container’s height could be way more important than its width.

That is of course until you remove the 100% property and replace it with the cover property e.g.:

div.div01, div.div02, div.div03 { 
    -webkit-background-size:cover; 
    -moz-background-size:cover; 
    background-size:cover;
}

Browser Support

Of course if you’re building for the latest browers then you have little to nothing to worry about.

background-size-css-responsive-design 

If you want to support IE8> then you need to turn to your old friend Javascript.

  • Backstretch – a simple jquery plugin that allows you to add a dynamically resized background to any page
  • Anystretch –  a jQuery plugin that allows you to add a dynamically-resized background image to any page or block level element.

Kudos to Elliot Jay Socks for the primer on this.

Subscribe to our Newsletter

Add your email address and receive an email every Friday covering off everything worth knowing about building your websites responsively.