opacity
Sets the transparency of the whole element together with its contents.
- Initial value
1- Inherited
- No
- Animatable
- yes, as a number
- Applies to
- all elements
- JavaScript
element.style.opacity = "0.5"
Example
#.card {
transition: opacity 0.2s;
}
.card:hover {
opacity: 0.8;
}
.card.locked {
opacity: 0.4;
pointer-events: none;
}<div style="display: flex; gap: 8px;">
<div class="box" style="transition: opacity .2s;">Module 1</div>
<div class="box" style="opacity: .4;">Module 2 π</div>
</div>Definition and usage
#The opacity property takes a number from 0 (fully transparent) to 1 (fully visible) or a percentage. It applies to the whole element: background, text, border and all children.
If you want only the background to be transparent while the text stays crisp, use a colour with an alpha channel, for example background-color: rgb(0 0 0 / 0.5), instead of opacity.
An element with opacity: 0 is invisible but still takes up space and can be clicked. A value below 1 also creates a new stacking context, which affects how z-index works.
Syntax
#opacity: <number 0-1> | <percentage>;Values
#Values in practice
#1
.demo { opacity: 1; }0.6
.demo { opacity: 0.6; }0.2
.demo { opacity: 0.2; }0
.demo { opacity: 0; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For a semi-transparent background under crisp text, use a colour with transparency, not
opacity. - Animations of
opacityandtransformare the cheapest for the browser. They work well for smooth fade-in effects.
Related entries
#- display vs visibility vs opacitydisplay: none removes an element from the layout, visibility: hidden hides it but keeps its space, and opacity: 0 makes it transparent, yet still clickable.
- visibilityHides an element but leaves behind the empty space it occupied.
- background-colorSets the background colour of an element.
- colorSets the text colour and the default colour of borders, decorations and SVG icons that use currentcolor.
- filterApplies graphical effects to an element: blur, brightness, contrast, greyscale and more.
- transitionA shorthand that makes CSS value changes happen smoothly instead of abruptly.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.