CSS Opacity
The opacity property sets how transparent an element is, from fully invisible to fully solid, affecting the element and everything inside it.
opacity takes a number from 0 to 1, where 0 is completely see-through and 1 is completely solid. A value of 0.5 makes the element half transparent, letting whatever sits behind it show through.
Basic transparency
A faded element
<!DOCTYPE html>
<html>
<head>
<style>
.faded {
opacity: 0.5;
}
</style>
</head>
<body>
<div class="faded">This element is faded</div>
</body>
</html>Note: opacity affects the whole element and all of its descendants, including text. If you only want a transparent background while keeping the text solid, use an rgba color instead.
Opacity vs rgba backgrounds
Transparent background, solid text
<!DOCTYPE html>
<html>
<head>
<style>
.overlay {
background: rgba(0, 0, 0, 0.6);
color: #fff;
}
</style>
</head>
<body>
<div class="overlay">
<p>Solid text over a see-through background</p>
</div>
</body>
</html>The fourth value in rgba is the alpha channel, which controls transparency for that color alone. Because it applies only to the background, the text stays fully opaque and readable.
A smooth hover fade
Fade on hover with a transition
<!DOCTYPE html>
<html>
<head>
<style>
.thumb {
opacity: 0.8;
transition: opacity 0.3s ease;
}
.thumb:hover {
opacity: 1;
}
</style>
</head>
<body>
<img class="thumb" src="thumbnail.jpg" alt="Thumbnail" width="150">
</body>
</html>- Use opacity for fade-in and fade-out effects and to dim disabled controls
- Use rgba or hsla when only a color needs transparency
- Remember that an element with opacity: 0 still occupies its space and can still be clicked
Exercise: CSS Opacity
What effect does opacity: 0.5 have on an element?