Opacity
Opacity CSS property is used to set transparency of an element. It defines how opaque an element is.
Its value can be anywhere in between 0 to 1. 0 means that the element is completely transparent and 1 means the element totally opaque. Opacity can also be defined in percentage, 0 to 100%, that resonates 0 to 1 value, which means 50% equals to 0.5 opacity for an element.
To understand opacity, let us take an example:
1. Create a division like below:
Image 2.8.1 Opacity Example |
2. Let us now add opacity:0.5. The division will look like this:
Image 2.8.2 After applying opacity to the div |
Opacity or background color with rgba value
In the Image 2.8.2, the text inside the division seems blurred due to the opacity of the division. This is why opacity is used whenever we need to make an image transparent or making overlays for a popup.
Now, what if we need a transparent background with text. For that, we can add the background color in rgba, where a is the alpha parameter which represents the opacity of the color applied. Like opacity alpha value lies between 0 and 1.
Setting color in rgba format
To get the rgba value of any color, open the web inspector, inspect the element, click on the square that appears besides the color, it will open color picker that allows to change the color format along with the color as shown below:
Image 2.8.3 How to open color picker from the web inspector |
Image 2.8.4 Color picker and changing the color format |
Image 2.8.5 Setting the alpha value |
Image 2.8.5 Removed opacity after setting the alpha value for rgba color |
Image 2.8.6 Original Image |
Image 2.8.7 Image with Overlay |
Pseudo Selector After/Before
The pseudo selectors after and before inserts a content before and after the HTML element respectively.
Pseudo selectors are used whenever there is no need to insert a complete new HTML element as in this example, there is no need to add an empty division to create this overlay (Image 2.8.7)
Syntax: