How to Stretch a Background Image in CSS

To stretch a background image in HTML, use the CSS background-size property or the background shorthand property.

Here's what the image looks like at its original size:

Background image 1a

The above example uses the background-size property to stretch the background image to 100% of the width, and 110% of the height, of its container. This is acheived by providing two values (i.e. 100% 110%), the first for the width and the second for the height.

You can also use other units, such as pixels, and you can use the contain or cover keywords to explicitly state how an image should fit to its container.

The cover Keyword

The cover keyword specifies that the background image should be scaled, 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.

The contain Keyword

The contain keyword specifies that the background image should be scaled, 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.

No Repeating

Again, the original image looks like this:

Background image 1a

You will be able to see from the above example that the image repeats if any of its sides is smaller than the image's container. Background images automatically repeat unless otherwise specified.

If you don't want your image to repeat, see how to make a background image not repeat.

Putting Styles into an External Style Sheet

The above example uses inline styles but could just as easily have used an external style sheet or an embedded style sheet (styles embedded in the document head).

If you place the background image code into an external style sheet, here's a snippet of what that might look like:

Here's a snippet of what the HTML code could look like:

Adding the above external style sheet will set a background image against the <body> element (which will typically result in the background image being applied to the whole page). In this case, the background image will stretch to the full width and height of the page (because I used background-size: 100% 100%;).

This example also sets a background image against a class that I called .myBox. Now, any HTML element that uses that class will have the background image applied to it, with its size set to contain.