CSS background property is used to define the background effects on element. There are 5 CSS background properties that affects the HTML elements:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
1) CSS background-color
The background-color attribute is employed to define the background color of the element.
You can set the background color like this:
<!DOCTYPE html>
<html>
<head>
<style>
h2,p{
background-color: #b0d4de;
}
</style>
</head>
<body>
<h2>My first CSS page.</h2>
<p>Hello C# Tutorial. This is an example of CSS background-color.</p>
</body>
</html>
Output:
My first CSS page.
Hello C# Tutorial. Here is an illustration of CSS background-color.
2) CSS background-image
The background-image attribute is utilized to designate an image as the background of a specific element. By default, the image spans the entirety of the element. You have the option to specify a background image for a webpage in this manner.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("paper1.gif");
margin-left:100px;
}
</style>
</head>
<body>
<h1>Hello C# Tutorial</h1>
</body>
</html>
Note: It is important to select a background image that complements the text color. Inappropriately pairing text and background images can result in a poorly designed webpage that is difficult to read.
3) CSS background-repeat
By default, the background-image attribute repeats the background image both horizontally and vertically. Certain images may be repeated solely in a horizontal or vertical direction.
The background appearance is enhanced when the image is solely repeated in a horizontal direction.
background-repeat: repeat-x;
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
</style>
</head>
<body>
<h1>Hello C# Tutorial</h1>
</body>
</html>
background-repeat: repeat-y;
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-y;
}
</style>
</head>
<body>
<h1>Hello C# Tutorial</h1>
</body>
</html>
4) CSS background-attachment
The background-attachment attribute determines whether the background image remains stationary or scrolls along with the content on the web page. When set to fixed, the background image remains static even when the page is scrolled. Let's illustrate this with an example featuring a fixed background image.
background: white url('bbb.gif');
background-repeat: no-repeat;
background-attachment: fixed;
5) CSS background-position
The background-position attribute determines the starting placement of the background image. By default, the background image is positioned at the top-left corner of the web page.
You can set the following positions:
- center
- bottom
- left
- right
background: white url('good-morning.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;