Opacity and alpha
Learn transparency with opacity and rgba/hsla.
The opacity property
opacity sets an element's transparency between 0.0 and 1.0. 1 is fully visible, 0 is fully transparent, 0.5 is half transparent.
Key point: opacity affects the whole element — text, background, border and any child elements. A semi-transparent card's text turns semi-transparent too. So when you only want the background transparent, rgba() is usually the better choice.
The alpha channel: rgba and hsla
The alpha channel bakes transparency into the color value itself. rgba(0, 0, 0, 0.5) takes a fourth value from 0 to 1; 1 is fully visible, 0 is fully transparent.
The same logic applies to hsla(): hsla(355, 78%, 56%, 0.4). This way you change only the color's transparency; text and other properties stay untouched. It is ideal for a semi-transparent layer over a dark background.
opacity vs alpha
opacity and rgba() look similar but work differently. opacity: 0.5 fades the entire element; text and everything else looks washed out.
background: rgba(0, 0, 0, 0.5) fades only the background; the text stays sharp. So you reach for rgba() to dim a layer behind a heading, and for opacity to fade a whole card.
Exercise Write transparency for .overlay and .card
Add a .overlay class selector and set its background property to rgba(0, 0, 0, 0.5). Then add a .card class selector and set its opacity property to 0.8.
Show example solution
/* add transparency for .overlay and .card */
.overlay {
background: rgba(0, 0, 0, 0.5);
}
.card {
opacity: 0.8;
}
Test yourself
-
What happens to a card with opacity: 0.5?
.card { background: white; opacity: 0.5; }- Only the background turns half transparent
- Only the border is affected
- The card's background, text and children turn half transparent
- The card becomes fully invisible
Show answer
The card's background, text and children turn half transparent — Correct. opacity makes the whole element and its children half transparent, not just the background.
-
Write the alpha value for a half-transparent overlay
.overlay { background: rgba(0, 0, 0, ____); }Show answer
.overlay { background: rgba(0, 0, 0, 0.5); } -
Match each transparency value to its effect
- opacity: 0.5
- Whole element half transparent
- rgba(0,0,0,0.5)
- Only color half transparent
- opacity: 0
- Element fully invisible
- rgba(0,0,0,1)
- Color fully visible