CSS Opacity Property
The CSS opacity property controls the transparency of an element. It determines how see-through an element is, affecting both the element itself and its content. Â
Purpose:
- The opacity property sets the level of transparency of an element.
- A value of 1 means the element is fully opaque (not transparent).
- A value of 0 means the element is completely transparent (invisible).
- Values between 0 and 1 create varying degrees of transparency.
Syntax:
element {
opacity: value;
}
- element: The HTML element you want to make transparent.
- value: A number between 0 (fully transparent) and 1 (fully opaque).
Example:
Fully Transparent:
.transparent {
opacity: 0;
}
Partially Transparent:
.transparent {
 opacity: 0.5; /* 50% transparency */
}
Fully Opaque (Default):
.transparent {
opacity: 1;
}
Important Considerations:
Inheritance: The opacity property is inherited by child elements. If you set opacity: 0.5 on a parent element, all its children will also be 50% transparent.
Interactivity: Even if an element is fully transparent (opacity: 0), it still occupies space on the page. However, the user cannot interact with it. Â
Alternatives for Background Transparency: If you only want to make the background of an element transparent without affecting its content, consider using rgba() or hsla() color values for the background-color property.
.background-transparent {
background-color: rgba(0, 0, 0, 0.5); /* Black background with 50% opacity */
}
Example HTML and CSS:
<!DOCTYPE html>
<html>
<head>
<title>CSS Opacity Example</title>
<style>
.box {
width: 200px;
height: 100px;
background-color: blue;
color: white;
text-align: center;
line-height: 100px;
margin: 20px;
}
.transparent {
opacity: 0.2;
}
.semi-transparent {
opacity: 0.6;
}
.background-transparent{
background-color: rgba(0,0,255,0.5);
}
</style>
</head>
<body>
<div class="box">Opaque</div>
<div class="box transparent">Transparent</div>
<div class="box semi-transparent">Semi-Transparent</div>
<div class = "box background-transparent">Background Transparent</div>
</body>
</html>
In the example above, you will see four blue boxes. The first one is solid blue, the second one is very see through, the third is more see through than the first but less than the second, and the fourth box has a see through background, but the text is still fully visible.