To add a background image in CSS, you use the background-image
property and
specify the image URL inside the url()
function. Here is the basic syntax:
css
selector {
background-image: url('path_to_your_image.jpg');
}
Steps and tips:
- The
path_to_your_image.jpg
can be a relative path (e.g.,"images/bg.jpg"
) or an absolute URL. - By default, the image will repeat to fill the element. To prevent repetition, use
background-repeat: no-repeat;
. - You can position the background image using
background-position
, for example,background-position: center center;
to center it. - To make the background image cover the entire element, use
background-size: cover;
. - To keep the background fixed when scrolling, use
background-attachment: fixed;
. - Always set a fallback background color with
background-color
in case the image fails to load.
Example:
css
body {
background-image: url('background.jpg');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
background-attachment: fixed;
background-color: #cccccc; /* fallback color */
}
This will add a centered, non-repeating background image that covers the entire viewport and stays fixed during scrolling
. You can also add multiple background images by separating URLs with commas:
css
body {
background-image: url('image1.png'), url('image2.png');
background-position: center, top;
background-repeat: no-repeat, repeat;
}
The first image is closest to the viewer, and the last one is furthest
. In summary, adding a background image in CSS involves using the background- image
property with the image URL, and optionally controlling repeat,
position, size, and attachment for the desired effect.