CSS Background Image
- The background-image property is used to add images as backgrounds for HTML elements.
- It allows developers to create attractive sections, banners, and website layouts.
- Background images are added using the CSS url() function.
- CSS provides additional properties to control image size, position, and repetition.
What is CSS background-image?
The CSS background-image property is used to set an image as the background of an HTML element.
It places the image behind the content of the element.
Background images are commonly used in website headers, hero sections, banners, cards, and full-page backgrounds to improve visual appearance.
CSS background-image Syntax
body {
background-image:
url("background.jpg");
}
Adding Background Image Using CSS
To add a background image, use the url() function inside the
background-image property. The image path can be a local file or an external URL.
div {
background-image:
url("image.jpg");
}
CSS background-image with Multiple Images
CSS allows you to apply multiple background images to a single element. Multiple images are separated using commas.
section {
background-image:
url("img1.png"), url("img2.png");
}
CSS background-repeat Property
By default, background images repeat horizontally and vertically.
The background-repeat property controls how the image repeats.
repeat
Repeats the image in both directions.
no-repeat
Displays the image only once.
repeat-x
Repeats the image horizontally.
repeat-y
Repeats the image vertically.
body {
background-repeat:
no-repeat;
}
CSS background-size Property
The background-size property controls the size of the background image.
It is useful for creating responsive designs.
cover
Scales the image to completely cover the element.
contain
Fits the complete image inside the element.
auto
Uses the original image size.
header {
background-size:
cover;
}
CSS background-position Property
The background-position property defines the starting position of the background image.
Common values include center, top, bottom, left, and right.
div {
background-position:
center;
}
Why Use CSS Background Image?
Website Design
Creates visually attractive website sections.
Hero Sections
Used for large banners and landing page designs.
Responsive Layout
Helps create flexible designs for different devices.
Better UI
Improves the overall user experience of websites.