How to Set a Background Image in HTML

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

The above example uses the background-image property to set the background image.

You must supply the location of the image, either as an absolute URL or a relative URL. Like this:

Change myimage.png to the location of your image.

Using the background shorthand property will allow you to add other background properties, such as color, background size, position, and more.

No Repeating

The original image in the above example looks like this:

Background image 2

So you will be able to see from the above example that the image is repeating, both vertically and horizontally. 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:

(Note that I use background-image on one line and background on the other — both will acheive the same result).

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).

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.