How to Set Opacity in CSS: Simple Guide with Examples
You set opacity in CSS using the
opacity property, which accepts a value between 0 (fully transparent) and 1 (fully opaque). For example, opacity: 0.5; makes an element 50% transparent.Syntax
The opacity property controls the transparency level of an element. It takes a number between 0 and 1:
0means fully transparent (invisible).1means fully opaque (no transparency).- Values like
0.3or0.75set partial transparency.
css
selector {
opacity: value;
}Example
This example shows a blue box with 50% opacity, making it semi-transparent so you can see the background behind it.
css
html {
height: 100%;
margin: 0;
}
body {
background-color: lightgray;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.box {
width: 200px;
height: 200px;
background-color: blue;
opacity: 0.5;
}Output
A blue square in the center of the page that looks half see-through, showing the light gray background behind it.
Common Pitfalls
One common mistake is thinking opacity only affects background color. It actually affects the whole element, including text and child elements.
To make only the background transparent but keep text fully visible, use rgba() color with alpha transparency instead.
css
/* Wrong: text also becomes transparent */ .transparent-box { background-color: blue; opacity: 0.5; color: white; padding: 20px; } /* Right: only background is transparent */ .semi-transparent-bg { background-color: rgba(0, 0, 255, 0.5); /* blue with 50% opacity */ color: white; padding: 20px; }
Output
Two boxes: the first with semi-transparent blue background and faded white text, the second with semi-transparent blue background but fully visible white text.
Quick Reference
Remember these key points when using opacity:
- Value range: 0 (transparent) to 1 (opaque).
- Affects entire element including children.
- Use
rgba()for background-only transparency. - Works on all visible HTML elements.
Key Takeaways
Use the CSS property
opacity with values from 0 to 1 to set transparency.opacity affects the whole element including text and child elements.For transparent backgrounds but solid text, use
rgba() colors instead of opacity.Values closer to 0 make the element more transparent; closer to 1 means more solid.
Opacity works on all visible HTML elements and is supported in all modern browsers.