Set the opacity for the background color with CSS

To set the opacity for the background color, use the RGBA color values or the opacity property. RGBA allows you to control the transparency of just the background, while the opacity property affects the entire element including text and child elements.

Syntax

/* Using RGBA for background opacity */
selector {
    background-color: rgba(red, green, blue, alpha);
}

/* Using opacity property */
selector {
    opacity: value;
}

Method 1: Using RGBA Values

The RGBA color model allows you to specify opacity only for the background color without affecting text or child elements. The alpha value ranges from 0 (completely transparent) to 1 (completely opaque) −

<!DOCTYPE html>
<html>
<head>
<style>
    div {
        padding: 20px;
        margin: 10px 0;
        color: #333;
        font-weight: bold;
    }
    
    .full-opacity {
        background-color: rgba(40, 135, 70, 1);
    }
    
    .medium-opacity {
        background-color: rgba(40, 135, 70, 0.6);
    }
    
    .low-opacity {
        background-color: rgba(40, 135, 70, 0.2);
    }
</style>
</head>
<body>
    <h3>RGBA Background Opacity</h3>
    <div class="full-opacity">Full opacity (1.0)</div>
    <div class="medium-opacity">Medium opacity (0.6)</div>
    <div class="low-opacity">Low opacity (0.2)</div>
</body>
</html>
Three green boxes appear with different background transparencies. The text remains fully visible in all boxes, while the background becomes increasingly transparent from top to bottom.

Method 2: Using Opacity Property

The opacity property affects the entire element, including background, text, and all child elements −

<!DOCTYPE html>
<html>
<head>
<style>
    div {
        background-color: #2887c8;
        padding: 20px;
        margin: 10px 0;
        color: white;
        font-weight: bold;
    }
    
    .opacity-full {
        opacity: 1;
    }
    
    .opacity-medium {
        opacity: 0.6;
    }
    
    .opacity-low {
        opacity: 0.3;
    }
</style>
</head>
<body>
    <h3>Element Opacity</h3>
    <div class="opacity-full">Full opacity (1.0)</div>
    <div class="opacity-medium">Medium opacity (0.6)</div>
    <div class="opacity-low">Low opacity (0.3)</div>
</body>
</html>
Three blue boxes appear where both the background and text become increasingly transparent. The entire element, including text, fades as opacity decreases.

Key Differences

Method Affects Background Affects Text Best For
RGBA Yes No Transparent backgrounds with readable text
Opacity Yes Yes Fading entire elements

Conclusion

Use RGBA values when you want transparent backgrounds while keeping text fully visible. Use the opacity property when you want to fade the entire element including all its content.

Updated on: 2026-03-15T12:26:23+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements