Setting the opacity of a background image in CSS involves using the background-image property along with the opacity property. By adjusting the opacity, you control the transparency of the background image, allowing elements behind it to partially show through, creating a visually layered effect.
We are using the following approaches to setting the opacity of the background image in CSS:
Table of Content
1. Using Opacity Property
The Opacity Property in CSS sets the transparency level of an element and its contents. Accepting values between 0 (fully transparent) and 1 (fully opaque), affects the entire element, including its children, making it a simple and effective way to control transparency in web design.
Syntax:
div {
opacity: 0.5;
}
Example: The opacity property in the CSS style of the “.element” class is set to 0.3, making the background image semi-transparent. This adjusts the visibility of the background while maintaining text readability.
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >Opacity of Background Image</ title >
< style >
.element {
width: 300px;
height: 200px;
background-image: url(
opacity: 0.3; /* Adjust opacity level */
color: white;
text-align: center;
line-height: 200px;
}
</ style >
</ head >
< body >
< h2 style = "color: green;" > GeeksForGeeks</ h2 >
< div class = "element" >
Background Image with Opacity
</ div >
</ body >
</ html >
|
Output:
2. Using Pseudo-elements:
To set the opacity of a background image in CSS using pseudo-elements, you can apply the opacity property directly to the pseudo-element’s background image, controlling its transparency independently from the element’s content.
Syntax:
selector::pseudo-element {
property: value;
}
Example: In this example the background image’s opacity is set using the ::before pseudo-element. Adjust the opacity level as needed. Ensure text visibility by positioning it above the pseudo-element using the z-index property.
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport"
content=" width = device -width,
initial-scale = 1 .0">
< title >Opacity of Background Image</ title >
< style >
.element {
position: relative;
width: 300px;
height: 200px;
color: white;
text-align: center;
line-height: 200px;
z-index: 1;
}
.element::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url(
opacity: 0.3; /* Adjust opacity level */
z-index: -1; /* Ensure background image is behind the text */
}
</ style >
</ head >
< body >
< h2 style = "color: green;" > GeeksForGeeks</ h2 >
< div class = "element" >
Background Image with Opacity
</ div >
</ body >
</ html >
|
Output: