How to Add Background Image in CSS?
Last Updated :
19 Nov, 2024
The CSS background-image property is used to add an image as a background to an element.
Syntax
background-image: url()
1. Setting background Image of an Element
A background image is added to an h1 tag using the URL.
HTML
<h1 style="background-image: url(
'https://media.geeksforgeeks.org/wp-content/uploads/20240701150351/HTML-Tutorial.webp');
height: 550px;width: 50%;">
This Element has a background image
</h1>
Output
Background-image2. Setting Background Size
The size of the background image can be set using the background-size property.
Syntax
background-size: value;
HTML
<body style="background-image: url(
'https://media.geeksforgeeks.org/wp-content/uploads/20240701150351/HTML-Tutorial.webp');
background-size: cover;">
<h1 >Image with background-cover</h1>
</body>
Output
background-cover3. Positioning the Background Image
The background-position property allows you to position the background image within the element.
Syntax
background-position: value
HTML
<h1 style="background-image: url(
'https://media.geeksforgeeks.org/wp-content/uploads/20240701150351/HTML-Tutorial.webp');
background-position: center; background-repeat: no-repeat; height: 500px; ">
Positioning the image
</h1>
Output
background-position4. Repeating Background Images
The repetition of the background-image can be set using the background-repeat property.
Syntax
background-repeat: repeat
HTML
<body style="background-image: url(
'https://media.geeksforgeeks.org/wp-content/uploads/20240701150351/HTML-Tutorial.webp');
background-repeat: repeat-x;">
<h1 >Background-repeat property</h1>
Output
Background-repeat property