How to use Pseudo-elements In CSS
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.
HTML
<!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( 'https://media.w3wiki.org/wp-content/uploads/20210313130410/exbg.png'); opacity: 0.3; /* Adjust opacity level */ z-index: -1; /* Ensure background image is behind the text */ } </ style > </ head > < body > < h2 style = "color: green;" > w3wiki</ h2 > < div class = "element" > Background Image with Opacity </ div > </ body > </ html > |
Output:
How to set the opacity of background image in CSS ?
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
- Using Opacity Property
- Using Pseudo-elements
Contact Us