CSS Background
We can use background properties to enhance the background style of the elements present in the HTML web page. CSS allows you to add multiple background images. In CSS background we can add color and alter the size of images.
Background Property
- background-color
- background-image
- background-repeat
- background-position
- background-attachment
background-color
Using CSS, you can easily set up a color scheme for your entire website or just tweak the colors of specific elements on a page. There are two key properties when it comes to assigning colors to elements using CSS - color and background-color. If you like, you also include background-color.
Syntax
<style>
body{
background-color: #0000ff;
}
</style>
background-image
With CSS you can specify a background image for any element and control exactly how it appears and is positioned. To add a background image to an element, use the background-image style property.
Syntax
<style>
div{
background-image: url('black_king.png');
height: 200px;
width: 200px;
border: 1px solid black;
background-color: #808080;
}
</style>
background-repeat
The background-repeat property is used to specify how background images are tiled. Options are:-
- repeat - the default, which tiles the image horizontally and vertically.
- repeat-x - tile horizontally only
- repeat-y - tile vertically only
- no-repeat
Example
<style>
div{
background-image: url('black_king.png');
height: 200px;
width: 200px;
border: 1px solid black;
background-color: #808080;
background-repeat: no-repeat;
}
</style>
background-position
The background property is a bit more complex than most you'll see. You can either pass in two percentages:-
horizontal position
- left
- right
- center
vertical position
- top
- bottom
- center
Example
<style>
div{
background-image: url('black_king.png');
height: 200px;
width: 200px;
border: 1px solid black;
background-color: #808080;
background-repeat: no-repeat;
background-position: center 40% / center top / bottom center / top right;
}
</style>
background-attachment
The final individual CSS property associated with backgrounds is background-attachment. It supports three values:
- scroll
- fixed
- local
Example
<style>
div{
background-image: url('black_king.png');
height: 200px;
width: 200px;
border: 1px solid black;
background-color: #808080;
background-repeat: no-repeat;
background-position: center 40%;
background-attachment: fixed;
}
</style>