Colors

Transparency

Color can be transparent


We can think about various situations where we want the color to be transparent. What is the difference between opacity and transparent color?


Opacity

CSS opacity property sets the opacity value for an element and all of its children (element content). This means that the parent has opacity that applies to everything within it. You cannot make a child element less transparent than the parent, without some trick. Note that if opacity is 0, you can not click on elements behind it; while in visibility: hidden, you can click on elements behind it.

The value of opacity is in the range from 0.0 (fully transparent) to 1.0 (fully opaque). For example the following sets all <div> content to be half transparent:

div { opacity: 0.5; }

Example:

In the following block the opacity is set to 0.2 on the container element. All the elements inside the container get this opacity (color, background, border ...). Hover the box below:

Opacity with Child Elements

Div Element

Paragraph Element

The block above is defined as:

HTML:
    <div class="container">
        <h4>Opacity with Child Elements</h4>
        <div>
            Div Element
            <p>Paragraph Element</p>
        </div>
    </div>
CSS:
    .container {
        opacity: 0.2;
    }
    .container:hover { opacity: 1; }

Transparency

CSS color in rgba/hsla format sets the opacity value only for a single declaration. For example the following sets <p> text only to be half transparent:

David DeSandro - Read color hex codes
p { color: rgba(128, 128, 128, 0.5); }

CSS transparent color value represents a fully transparent color, i.e. the color seen will be the background color. Technically, it is a black with alpha and is a shortcut for rgba(0,0,0,0).

Example: By using transparent color we can, for example, generate blured text like the following:

Please
Hover Me

The "Please Hover Me" <p> text is defined as:

CSS:
    p {
        color: transparent;
        text-shadow: 0px 0px 2px rgba(0, 0, 0, 0.5);
    }
    p:hover { color: blue; }

Example: In the following example we add color with transition (will learn later) to the border on hover. It is widely used in navigations:

Hover Me

The "Hover Me" <p> text is defined as below. See also as the element color is used on the border by specifying the currentColor:

CSS:
    p {
        border-bottom: 2px solid transparent;
        color: blue;
    }
    p:hover {
        border-bottom: 2px solid currentColor;
    }