By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

How to make a background-image Stretch

This Tutorial shows how to make a background-image stretch and scale as a page or element is re-sized.

Edited: 2012-06-25 04:13

Making a background image stretch to take up all available space has been no easy task, you may remember BlueBoden's early attempt – which can be seen here – but it did not appear to work as intended, so he eventually abandoned attempts. Now, new CSS properties are being supported in browsers, that is the background-size property for one, making new things possible.

The background-size property allows you to set how much space the background should take up. There are two keywords, contain and cover, wheres we will be using cover in this Tutorial. The contain keyword is used to make the background image not exceed the background positioning area, while cover will allow the background image to become greater than or equal to the positioning area.

The property also accepts a length value, so that you can precisely specify how large the background should be, and the best thing is, it will automatically be scaled up or down to fit!

To make a background image stretch and re-size together with the rest of the page, you can use the below CSS.

html { 
  background: url("my-background.png") no-repeat center center fixed;
  background-size: cover;
}

If this does not yet work in your browser, you can try to use the prefixed versions as well.

html { 
  background: url("my-background.png") no-repeat center center fixed;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  -o-background-size: cover;
}

The below is a fully working cover example, including the HTML markup and the embedded css code.

<!DOCTYPE html>
<html lang="en-US">

  <head>
    <title>Background-image Stretch CSS - Vision Example</title>
    <style type="text/css">
html { 
  background: url("http://brugbart.com/examples/mappen-billeder/ScratchBG.png") no-repeat center center fixed;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
    </style>
  </head>

  <body>
      <h1>Stretch a Background - HTML and CSS Example</h1>
      <p>This example shows how you can make a background-image Stretch to fill the entire browser window, it will automatically re-size together with everything else as the browser window is made smaller or bigger.</p>
  </body>

</html>

Background-image Stretch - Vision Example