iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Opacity

opacity fades an element — and everything inside it — from fully visible (1) to fully transparent (0). Anything in between blends with the background.

The opacity scale

1.0 0.75 0.5 0.25 ~0
Fig 1. The same green at five different opacities.

opacity vs alpha vs visibility

TechniqueAffects children?Takes up space?
opacity: 0.5Yes — fades the whole subtree.Yes — still in the layout, still interactive.
background: rgb(4 170 109 / 0.5)No — only the background channel.Yes.
visibility: hiddenHides whole subtree.Yes — still occupies space, not interactive.
display: noneRemoves the box.No.
Tip: Setting opacity below 1 creates a new stacking context. Combined with z-index that can cause "why is my modal behind something" puzzles — see z-index.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Opacity</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Fade this image to 50%.

img.faded { : 0.5; }

Test yourself

Q1. Does `opacity: 0.5` affect children?
Q2. Which technique fades only the background colour, not the children?
Q3. A fully transparent element with `opacity: 0` still…

Discussion

Loading…