CSS Opacity

Transparency of elements on the web-page can be used to imply their state, notify some change or just as a styling effect.

The opacity property can help us alter the transparency of the element. We can set values in the range 0.0 – 1.0 where 0 being completely transparent.


Hover Effect

One of the common uses of the opacity property is together with the :hover selector.

For instance, you can use an image for the navigation list and change the opacity on hover so that the image isn’t transparent when you hover over it and when you move the mouse pointer away, the image turns transparent again.

A similar effect can be given for the image thumbnails on the web pages (like a profile picture or an image search)


Box Transparency

The opacity property controls the transparency of the whole box.

Imagine if you use the property to alter the transparency of an element’s background.

Then, in that case, all its child elements will also inherit the same properties.

This can cause issues like unreadable text due to high transparency.

To resolve this, we can give the background-color in RGBA values.

Here, along with the old RGB values, we also have the Alpha value that states the opacity of the background.

Thus RGBA will set the opacity for the background color without affecting the text.

A sample code would be like:


There’s another way of deliberately putting text in a transparent box. We can create a <div> with a specified class, like class= “flowers” etc.

Inside this <div> we will create another <div> with some other class like class = “opaBox” and finally,

inside this div we can specify the properties for a <p> element so that the text is readable without being affected by the containing <div> element’s opacity values.