CSS RGB and HSL

In CSS, two of the most flexible and commonly used color systems are RGB and HSL. These systems allow you to define colors with precision and even add transparency for creative effects.

1. RGB Colors

RGB stands for Red, Green, and Blue. It works by mixing these primary colors to create a wide range of colors. You can define RGB colors using the rgb() function.

CSScopy
/* Example: RGB Colors */
h1 {
  color: rgb(255, 0, 0); /* Pure red */
}

div {
  background-color: rgb(0, 255, 0); /* Pure green */
}

You can also include transparency using rgba(), where the fourth value (alpha) controls transparency:

CSScopy
/* Example: RGBA Colors */
p {
  background-color: rgba(0, 0, 255, 0.5); /* Semi-transparent blue */
}

2. HSL Colors

HSL stands for Hue, Saturation, and Lightness. It provides a more intuitive way to define colors. The hsl() function takes three parameters:

  • Hue: The base color, measured in degrees (0-360). For example, 0 is red, 120 is green, and 240 is blue.
  • Saturation: The intensity of the color, measured as a percentage (0% is grayscale, 100% is full color).
  • Lightness: The brightness of the color, measured as a percentage (0% is black, 100% is white).
CSScopy
/* Example: HSL Colors */
div {
  color: hsl(120, 100%, 50%); /* Vivid green */
}

Similar to RGBA, HSL also supports transparency with hsla():

CSScopy
/* Example: HSLA Colors */
div {
  background-color: hsla(240, 100%, 50%, 0.5); /* Semi-transparent blue */
}

3. RGB vs. HSL

Use RGB when you work with tools that provide RGB values or when precision is needed for gradients. Choose HSL when you want to experiment with lightness or saturation easily.

Know someone who'd find this guide helpful? Please share!

Page 12 of 25

Page 12 of 25

logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and so much more. Practice your skills with our free games, examples, practice questions & quizzes

    © 2024 Tomilola Group
    • facebook logo
    • twitter logo
    • instagram logo
    • linkedin logo
    • github logo
    • youtube logo