CSS Opacity/Transparency
- Previous page CSS Pseudo-elements
- Next page CSS Navigation Bar
opacity
The attribute specifies the opacity/transparency of the element.
Transparent image
opacity
The range of the value of the attribute is 0.0-1.0. The lower the value, the more transparent:

opacity 0.2

opacity 0.5

opacity 1
Example
img { opacity: 0.5; }
Transparent hover effect
opacity
The attribute is usually combined with :hover
Selector is used together, so that the opacity can be changed when the mouse hovers:



Example
img { opacity: 0.5; } img:hover { opacity: 1.0; }
Example explanation
The first CSS block is similar to the code in Example 1. In addition, we have added an effect when the user hovers over one of the images. In this case, when the user hovers over the image, we want the image to be opaque. This CSS is opacity:1;
.
When the mouse pointer leaves the image, the image will become transparent again.
Example of reverse hover effect:



Example
img:hover { opacity: 0.5; }
Transparent box
Using opacity
When the opacity property is used to add transparency to the background of an element, all its child elements inherit the same transparency. This may make the text within completely transparent elements difficult to read:
Example
div { opacity: 0.3; }
Using RGBA opacity
If you do not want to apply opacity to child elements, as in the example above, use RGBA color values. The following example sets the background color instead of the text opacity:
You have learned from our CSS Colors In this chapter, we learned that RGB can be used as color values. In addition to RGB, RGB color values can also be used with an alpha channel (RGBA) - this channel specifies the opacity of the color.
RGBA color values are specified as: rgba(red, green, blue, alpha) alpha The parameter is a number between 0.0 (completely transparent) and 1.0 (completely opaque).
Tip:You will learn in our CSS Colors In this chapter, we learn more about RGBA colors.
Example
div { background: rgba(76, 175, 80, 0.3) /* Background with 30% opacity in green */ }
Text within a transparent box
This is some text located within a transparent box.
Example
<html> <head> <style> div.background { background: url(klematis.jpg) repeat; border: 2px solid black; } div.transbox { margin: 30px; background-color: #ffffff; border: 1px solid black; opacity: 0.6; } div.transbox p { margin: 5%; font-weight: bold; color: #000000; } </style> </head> <body> <div class="background"> <div class="transbox"> <p>This is some text located within a transparent box.</p> </div> </div> </body> </html>
Example explanation
Firstly, we create a <div> element with a background image and border (class="background").
Then, we create another <div> inside the first <div> (class="transbox").
<div class="transbox"> has a background color and border - this div is transparent.
Inside a transparent <div>, we added some text within the <p> element.
- Previous page CSS Pseudo-elements
- Next page CSS Navigation Bar