content logo

Learn CSS:

CSS opacity

The CSS opacity property can be used to set the opacity / transparency of an HTML element. Opacity is the opposite of transparency so the more opaque an HTML element is, the less transparent it is.

Opacity is specified as a number between 0 and 1. The value 0 means fully transparent (no opacity), and the value 1 means fully opaque. Similarly, the value 0.5 means semi-opaque, which is the same as semi-transparent.

Here is an opacity CSS property example:

.withOpacity {
    opacity: 0.5;
}

This examples sets the opacity of all HTML elements with the CSS class withOpacity to 0.5 meaning the HTML elements become semi-transparent.

Here is a visual example of a div element with a background image, containing another div element with a red background and some white text. The inner div element has its opacity set to 0.7:

This div element is semi-transparent.

Notice how you can see the background image of the outer div element through the red background and white text of the inner div element.

The code used to generate the above CSS opacity example is:

<div style="background-image: url('/images/css/border-image.png'); 
            background-size: 100% 100%; height: 200px;">
    <div style="opacity: 0.7; font-size: 3.0em; 
                background-color: #ff0000; color: #ffffff;">
        This div</code> element is semi-transparent.
    </div>
</div>

Opacity of Nested Elements

If you set the opacity of an HTML element and that element has children (nested elements), then the maximum opacity the nested elements can have is the same as the parent element. For instance, if you set an opacity of 0.7 on the outer element (the parent) then all children can maximally have an opacity of 0.7.

There are ways to work around this. For instance, you can set the background color of the parent element to a color with transparency (see CSS colors). Then only the parent's background color will be transparent. All nested elements will be fully opaque.

You can also place an opaque element on top of a semi-transparent element using the CSS position property. The opaque element is thus technically not child of the semi-transparent element, but it will look as if it were.

#

Css Opacity Example

#

Css Opacity Code

#

Css Opacity Tutorial