Open In App

CSS – How To Set Opacity Of Background Image?

Last Updated : 04 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the different ways to set the opacity of the background image

1. Using Opacity Property

The opacity property in CSS is a simple way to adjust the transparency of an element. You can set its value between 0 (completely transparent) and 1 (fully opaque).

Syntax

div {
opacity: 0.5; /* Adjusts transparency for the entire element */
}
HTML
<!--Driver Code Starts{-->
<html>
<head>
<!--Driver Code Ends }-->

    <style>
        .element {
            width: 300px;
            height: 200px;
            background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20210313130410/exbg.png');
            opacity: 0.3;
            color: white;
            text-align: center;
            line-height: 200px;
        }
    </style>

<!--Driver Code Starts{-->
</head>
<body>
    <h2 style="color: green;"> GeeksForGeeks</h2>
    <div class="element">
        Background Image with Opacity
    </div>
</body>
</html>
<!--Driver Code Ends }-->

Output

OpacityofBackgroundImage

Using Opacity Property

2. Using Pseudo-elements

To make a background image transparent without affecting the element’s content, you can use pseudo-elements like ::before or ::after and apply the opacity property to them.

Syntax

selector::pseudo-element {
property: value;
}
HTML
<!--Driver Code Starts{-->
<html>
<head>
<!--Driver Code Ends }-->

    <style>
        .element {
            width: 300px;
            height: 200px;
            background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20210313130410/exbg.png');
            opacity: 0.3;
            color: white;
            text-align: center;
            line-height: 200px;
        }
    </style>

<!--Driver Code Starts{-->
</head>
<body>
    <h2 style="color: green;"> GeeksForGeeks</h2>
    <div class="element">
        Background Image with Opacity
    </div>
</body>
</html>
<!--Driver Code Ends }-->

Output:

ImageOpacity

Using Pseudo-elements



Next Article

Similar Reads