Background
The background is an essential element for enhancing the visual features of a web page.
Using various background properties in CSS, such as background-color, background-image, and background-position, you can create a vibrant background for your web page.
background-color
The background-color property specifies the background color of an element.
div {
background-color: pink;
}
This will set the background color of the div to pink.
background-image
Sets an image as the background of an element.
div {
background-image: url('https://picsum.photos/500');
}
As shown above, you can set an image as the background for a div by specifying the path to the image.
background-repeat
Determines whether or not the background image is repeated.
-
repeat: Repeats the image both horizontally and vertically -
repeat-x: Repeats the image only horizontally -
repeat-y: Repeats the image only vertically -
no-repeat: Does not repeat the image
div {
background-image: url('https://picsum.photos/600');
background-repeat: no-repeat;
}
This example shows the background image displayed only once without repeating.
background-position
Specifies the position of the background image. You typically set the values for the x and y axes to adjust the position.
div {
background-image: url('https://picsum.photos/600');
background-position: center center;
}
This positions the image at the center of the div.
background
The background property allows you to set all the background properties mentioned above in one declaration.
div {
background: pink url('https://picsum.photos/200') no-repeat center center;
}
Follow the highlighted parts in the code to try it yourself.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.