In this article, we will learn how to set the position of a background image with the help of examples. To do so, firstly, we will demonstrate the procedure of adding an image as a background in CSS.
Add Background Images Using “background-image” Property
For adding images in the background, the “background-image” property is utilized.
Syntax
Following is the syntax to set a background image to an HTML element:
Here, “url()” specifies the image name or image folder path in which it exists.
Now, move to the practical example of using the background-image property.
Example: Inserting a Background Image Using CSS
In this example, we will create an <h1> element, and background will be added behind this element. You can add elements according to your choice and apply the background-image property to it:
After that, move to the CSS, use the “background-image” property, assign the image path or name in the as “url()” value of the background-image property:
background-image: url("img.jpg");
}
This will give the following outcome:
This is how you can add a background image in CSS.
How to Center Background Images Using “background-position” CSS Property?
The “background-position” property sets the background image’s position. The syntax will be as follows:
The image’s position can be specified as absolute, left, or right. More specifically, setting the “center” value will center the added background image.
Now, let us move to the practical example that demonstrates how to use the background-image and background-position properties in CSS.
Example: How to Set Background Image in Center?
We will set the background color and image path with the “background” property. Next, we will utilize the “background-position” property to set the background image in the center. Finally, we will set the “background-repeat” property to no-repeat for not repeating the image:
background: rgb(128, 44, 12) url("image.jpg") fixed;
background-position: center;
background-repeat: no-repeat;
}
Once it is all done, execute the code, and let’s have a look at the final outcome:
Our background image is successfully positioned in the center of the page.
Conclusion
Background images can be added using the background-image property, whereas background position can be set using the background-position property. To the center, the background image in CSS sets the value of the background-position property to “center”. The article explains in detail how to add an image to the background using “background-image” and how to set its position using the “background-position” property.