rgb() / rgba()

Term side of the Card.
Topic: Colors
Unit title: rgb() / rgba()
Categories: Function
Explanation side of the Card

Explanation: The functions that define colors with red, green and blue channels, like `rgb(255 136 0)`. An optional alpha value after a slash adds transparency, like `rgb(0 0 0 / 50%)`, while `rgba()` is an older alias that works the same way.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 1.
Availability: 

Example

Wrongcss
.overlay {
  background: rgb(0 0 0);
  opacity: 0.5;
}
Rightcss
.overlay {
  background: rgb(0 0 0 / 50%);
}

Alpha in the color fades only the background, while opacity also fades the text and children.

Common mistakes

  • Mixing commas with the slash, which makes the color invalid.
  • Using opacity to fade a background, which also fades the text.

Key points

  • Code uses the space-separated form rgb(0 0 0 / 50%) rather than rgba() with commas.
  • Commas and the slash are not mixed in one function, like rgb(0, 0, 0 / 50%).
  • When only the background should fade, alpha goes in the color, not in opacity.

Interview questions

What is the difference between rgb() and rgba()?

None in practice. Both accept an alpha value, and rgba() is kept as an alias of rgb().

Can rgb() values be percentages?

Yes, like rgb(100% 50% 0%). The space syntax allows mixing numbers and percentages; the comma form needs all channels of one type.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy