CSS Opacity
1 April 2025 | Category: CSS
The opacity
property in CSS controls the transparency level of an element.
It takes a value from 0 (completely transparent) to 1 (fully visible).
🔹 1. Basic Usage
.element {
opacity: 0.5; /* 50% transparent */
}
✅ This makes the element semi-transparent.
🔹 2. Opacity Values and Effects
Opacity Value | Effect |
---|---|
opacity: 1; | Fully visible (default) |
opacity: 0.5; | 50% transparent |
opacity: 0.2; | Almost invisible |
opacity: 0; | Completely hidden |
🔹 3. Opacity on Images
img {
opacity: 0.7; /* 70% visible */
}
✅ The image becomes slightly transparent.
🔹 4. Opacity with Hover Effect
button {
opacity: 1; /* Fully visible */
transition: opacity 0.3s;
}
button:hover {
opacity: 0.5; /* Becomes 50% transparent on hover */
}
✅ The button becomes semi-transparent when hovered.
🔹 5. Opacity and Background (Problem & Solution)
🔴 Issue: When you set opacity
on a parent, it affects all child elements.
.container {
background-color: red;
opacity: 0.5;
}
✅ Solution: Use rgba()
for only background transparency, keeping text 100% visible.
.container {
background-color: rgba(255, 0, 0, 0.5); /* Red background with 50% opacity */
}
📌 Conclusion
opacity
makes elements transparent.- It affects everything inside the element.
- Use
rgba()
instead of opacity if you only want a transparent background.