HTML Stretch Background Image

This article provides HTML code to enable you to stretch a background image.

CSS3 introduced a new property — background-size — that enables you to change the size of background images. That means you can stretch your image horizontally, vertically, or both. You can resize it any way you wish.

For example, you can have the background image stretch (and contract) to whatever size the element is that it is applied against.

In the following example, we use provide background-size with a value of 100% 100%, which means that it is the same size of the element — regardless of how big the actual image is.

Stretching the Background Image for the Whole Page

The above example uses a background image applied against a <div> element. You can also apply it against the <body> element, therefore resulting in the image stretching to fill the the whole page.

You might need to set the <body> and <html> elements' height property to 100%.

Increase the Size without "Stretching" the Image out of Proportion

The background-size property also accepts values that prevent the image from stretching out of proportion.

Using background-size: cover

You can use background-size: cover to scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

Using this option will ensure that the image doesn't get stretched out of proportion. Bear in mind, parts of the image may be hidden if the element has different proportions to its background image.

Using background-size: contain

You can use background-size: contain to scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

Using this option will ensure that none of the image is hidden as it scales up or down.

Using CSS Layers

Although the background-size property is the recommended way to stretch your background images, this property hasn't always been around.

Before this property was invented, you needed to use a bit of trickery to acheive the "stretched background image" effect.

One method was to use a normal <img> element and then layer it so that it appeared to be a background image.

If for any reason you can't/don't want to use the background-size method, check out how to stretch a background image using layers.