CSS Backgrounds
The CSS background properties are used to add background effects for elements.
In these chapters, you will learn about the following CSS background properties:
background-colorbackground-imagebackground-repeatbackground-attachmentbackground-positionbackground(shorthand property)
These properties help you design visually appealing backgrounds for your HTML elements. Let me know if you'd like to dive into any specific property!
CSS background-color
The background-color property specifies the background color of an element.
Example
The background color of a page is set like this:
body {
background-color: lightblue;
}CSS Background Color for Other Elements
With CSS, a color is most often specified by:
- a valid color name - like
"red" - a HEX value - like
"#ff0000" - an RGB value - like
"rgb(255,0,0)"
Look at CSS Color Values for a complete list of possible color values.
Other Elements
You can set the background color for any HTML element:
Example:
Here, the <h1>, <p>, and <div> elements will have different background colors:
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}Opacity / Transparency
The opacity property specifies the opacity (transparency) of an element. It can take a value from 0.0 (fully transparent) to 1.0 (fully opaque). The lower the value, the more transparent the element becomes.
Example:
div {
background-color: green;
opacity: 0.3;
}Transparency using RGBA
If you do not want to apply opacity to child elements (like in the previous example), use RGBA color values. The following example sets the opacity for the background color but not the text.
Example:
- 100% opacity
- 60% opacity
- 30% opacity
- 10% opacity
You learned in the CSS Colors chapter that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color.
An RGBA color value is specified with:
rgba(red, green, blue, alpha)Transparency using RGBA Example
div {
background: rgba(0, 128, 0, 0.3); /* Green background with 30% opacity */
}