CSS background-image Property Tutorial

In this section, we will learn what the background-image property is and how to use it in CSS.

Click here to run the example of background-image property.

CSS background-image Property Definition and Usage

Sometimes we want to have an image as the background of an element like <p> or <div> or <nav> or <article> etc. This is where CSS `background-image` property comes in.

CSS background-image Property Syntax

background-image: url|none|initial|inherit;

CSS background-image Property Value

The value of the `background-image` property is the URL address of one or more image files that we want to set as the background of an element.

Note: if we used multiple images for the background of an element, we should use ‘,’ in order to separate the address of each image from the other.

Example: background image in CSS

See the Pen background image in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.

How Does CSS background-image Property Work?

The images we’ve used for the example above are:

<img src="https://www.enjoytutorials.com/hotlink-ok/photos/spider.jpg"> and <img src="https://www.enjoytutorials.com/hotlink-ok/photos/face.jpg"> and <img src="https://www.enjoytutorials.com/hotlink-ok/photos/heart.jpg">

As you can see, these background images are repeated to fill the entire space of their elements.

This is the default behavior of browsers to tile the background-image until it fills the entire space of its element.

We can control this tilling using `background-repeat` property, which is covered in the `background-repeat` section.

Example: image as background in CSS

See the Pen image as background in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.

As you can see in this example, we used ‘,’ to separate the address of each image from the other.

Note: don’t worry about `background-position` and `background-repeat` properties; these are covered in their section.

CSS background Image URL

The address of an image file could be either relative or absolute for the background-image property.

If the file is in the same server as the webpage, then using relative URLs is better than using the absolute URL of that image.

But if the target image is in another server, then the only option would be using the absolute URL of that image file.

Example: CSS background URL image

See the Pen CSS background URL image by Enjoy Tutorials (@enjoytutorials) on CodePen.

In this example, the background image of the <div> element in this example is an external image file (From another server) and hence we needed to use the absolute URL of that image.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies