Back

Color types in CSS

Color types in CSS

Spot me an object which can’t be attributed to a color! None right? That shows the efficacy of colors in our day-to-day living.

Colors are important design components as they help produce visually appealing and accessible web pages. As a Web developer, you should understand the different color models in CSS as it helps in implementing effective designs. With the wide range of color types available, knowing where to start is overwhelming, but don’t worry! This article is here to help you navigate the world of colors in CSS.

In this guide, we will take an in-depth look at the different color types available in CSS. We’ll start by discussing the different color types available in CSS, such as named colors, RGB, and HSL values. We’ll cover additional topics such as RGBA, HSLA, and using the currentColor keyword in CSS.

By the end of this guide, you will have a solid understanding of using colors in CSS effectively. Let’s dive in and explore the world of color in CSS!

Color Syntax in CSS

The color specification in CSS is relatively simple but solely depends on the color type. The most common ways to define colors in CSS are using named colors, hexadecimal values, RGB, and HSL values. Each type of color notation has its syntax and rules for defining colors, but they all follow the same basic structure of being a property value representation.

We use the color property in CSS to set the color of text content within an element. The syntax for using the color property is

element {
  color: value;
}

Where element is the HTML element you want to apply the color, and value is the color value you want to set. The value can be any of the color types we discussed earlier, such as named colors, hexadecimal values, RGB, and HSL. For example, the following CSS syntax sets the text color of an element to red:

element {
  color: red;
}

or

element {
  color: #ff0000;
}

or

element {
  color: rgb(255, 0, 0);
}

We also apply the color property to other CSS properties, such as background-color, border-color, and outline-color in controlling the color of these visual elements.

currentColor Keyword

The currentColor keyword in CSS is a significant method used in controlling the color of multiple elements at once. With the currentColor keyword, you can easily set the color value with a single line of code, making your stylesheets more efficient and maintainable.

The currentColor keyword refers to the computed value of the color property for an element, and it returns the color value of that element. For example, if you set the color property as red, properties in that element that use currentColor will have that same color (red in this case). It eliminates the need to set the color of each element separately, making it more efficient and easier to maintain the code.

Usage For example, let’s say you have a button class in which you must have the same color for both text and border. Instead of setting the color for both the text and border separately, you can use the currentColor keyword for the border color, like so:

.button {
  color: green;
  border: 3px solid currentColor;
}

In the example above, we set the text color to green and the border color to the same color (green) using the currentColor keyword. If you change the text color to red, the border color will also change to red automatically. We no longer need to set the border color separately, making maintaining the code more efficient and easier.

Drawback We can use the currentColor keyword with other properties, such as background-color, background-image, box-shadow, and so on. But it has a little tweak when it is used to determine other color property values like border.

The currentColor keyword only works for the color property. If you want to use it with other properties such as background-color, you will need the var() function.

For example:

.element {
  background-color: red;
  border: 2px solid currentColor;
}

In the code above, the border for the button will remain black since the currentColor keyword doesn’t inherit colors from other properties besides the color property itself.

But if we implement the color property, the currentColor keyword works.

.element {
  color: blue;
  background-color: red;
  border: 2px solid currentColor;
}

Now, the currentColor keyword works, and the border will inherit the value of the color property as its value (2px solid blue in this case).

The currentColor keyword is a powerful tool that helps you create consistent and efficient designs with less code. It allows you to set color values once and reuse them throughout your stylesheet, ‌hence implementing the DRY (Do Not Repeat Yourself) principle. It is a great way to keep your code organized and maintainable.

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data. Check our GitHub repo and join the thousands of developers in our community.

The Color Types

There are diverse ways by which we can define colors in CSS. In this section, we will look at some specific color types in CSS and also explore the benefits and drawbacks of each. Here are the color types to be discussed:

  • Color Keyword/Named Colors
  • RGB (HEX)
  • HSL
  • RGBa
  • HSLa

Color Keyword/Named Colors

Named color, also known as the color keyword, is a straightforward method of defining color in CSS. Named colors are predefined keyword that corresponds to specific color values. For instance, the color keyword red corresponds to the color value #FF0000.

CSS provides a set of predefined named colors, such as azure, beige, bisque red, blue, green, yellow, and so on. Browser support for the color keyword is top-notch, as all modern browsers support it. With that, you can confidently use the color keyword method in defining colors, knowing fully well that they will be displayed correctly across various platforms.

Just as it is defined, here is the syntax for using the named color:

element {
  color: red;
}

In the code snippet above, we used the color keyword method to define a color for an element.

The color keyword is not limited to setting the color property but also defining other properties, such as background color and border color.

Benefits

  1. Usage: This color type is easy to use since they are predefined keywords. Developers do not need to memorize color values to use them.
  2. Browser Support: Modern browsers supports them, making them a convenient and versatile option.
  3. Maintainability: You can easily update the color value of an element by changing only that color value at that instance instead of searching for all occurrences of that color value throughout the stylesheet. Hence, the color scheme of your web build is easy to maintain.
  4. Case Insensitive: CSS color keywords are not case sensitive, disallowing bugs in our stylesheet. For example, red, Red, and RED will all result in the color value #FF0000.

Drawbacks One major drawback of using named colors is that they do not have a standard definition across different platforms and devices. The appearance of the same named color across devices or browsers might be fully or partially different, which makes it hard to achieve consistent designs across various devices or browsers.

Note: the color keyword should be used more in places where you do not need to control the transparency of the color since it does not allow you to specify an alpha channel value.

RGB

RGB is an additive color model that creates colors via a mixture of red, green, and blue light. This color system accepts three parametric values - red, green, and blue. Each value can be a number between 0 and 255, where 0 represents no color and 255 represents the maximum amount of color. It’s also possible to use percentage values instead of integer values - the values range from 0% to 100%. For example, we can represent the red color in RGB as rgb(100%, 0%, 0%).

We have two ways to express RGB color values: hexadecimal and functional notation.

  • Hexadecimal notation It is commonly called HEX code, a 6-digit code prefixed with the # symbol followed by three pairs of hexadecimal digits, where the pairs represent the amount of red, green, and blue light. Each value is within the range 00 - FF or 0 - 255 in decimal notation.

The syntax:

element {
  color: #rrggbb;
}

Note: you can also specify each range value with a single value of red, green, and blue. It is valid. See the syntax below:

element {
  color: #rgb;
}

That HEX code originates from the RGB color model makes it entitled to conversion to an RGB value and vice versa. We can calculate the RGB values of a HEX color by converting the two-digit hexadecimal values for red, green, and blue to decimal values. For example, the HEX color #ff0000 is equivalent to the RGB color rgb(255, 0, 0).

Apart from being shorter than RGB values, HEX values also have some added advantages, such as:

  1. Consistency: HEX codes are consistent across different platforms and devices, i.e., the color does not vary across various platforms.
  2. Widely supported: They are supported by all modern web browsers, making them a reliable and versatile choice for web developers.
  3. Easier to convert: we easily convert them to RGB values. Hex values also have some drawbacks, such as:
  4. Limited range of colors: HEX color has a limited range of colors compared to other color methods. The total number of colors HEX notation provides - 256 ^ 3, equivalent to 16,777,216.
  5. Complexity: HEX values are hard to comprehend. We often find HEX values complex to interpret, as we can not easily deduce the color.
  6. Precision: HEX values are less precise than RGB values, which makes it difficult to interpret or specify the exact color you want without using a color picker tool.
  • Functional notation RGB and RGBa are functional notations. These two methods end with the opening ( and ) braces. It symbolizes a function, just as we have in programming languages like JavaScript. In subsequent sections of this article, we will look into the RGBa method. All you have to know is that RGBa is a higher level of RGB; the only difference is the additional alpha value that determines the opacity of the defined color.
    • RGB: As I mentioned earlier, this is a color scheme that takes three parameters, namely red, green, and blue values, just as its name suggests. This color model is very easy-to-use and human-friendly since we know that the integer 0 means we are not using that color, while the integer 255 or 100% means we used all that color. With the use of RGB, some colors can be easily determined - white and black. From the explanation above, you will agree with me that if we want to define a white color, all we have to do is initiate the max value for each of the three parameters, just like this:
.element {
  color: rgb(255, 255, 255);
  color: rgb(100%, 100%, 100%);
}

The code snippet above will result in a text color of white. And for black, we will set the values of the three parameters to the least value in the range (0 - 255).

.element {
  color: rgb(0, 0, 0);
}

The code snippet above will result in a text color of black. We believe that the primary colors (red, green, and blue) are the easiest to define since you only need to set the color values of the two other color parameters you do not need to 0, while the value of the one you need in the range integer 1 - 255.

RGB color model has various advantages, such as a wide range of colors, flexibility of setting colors from very pale shades to very intense ones, a good option for creating color gradients, and great support across all modern web browsers and devices. On the other hand, the RGB color model has some drawbacks, such as complexity, being less intuitive when compared to the color keyword method, and precision (since RGB are in decimal, it is hard to define a particular color without the use of a color wheel).

HSL

The fact that it is hard to decipher some color models, such as HEX and RGB (in a way), leaves us with an option to find a color model which is more readable and easily understandable by humans. Here is where HSL comes into the picture.

HSL is an abbreviation that stands for hue, saturation, and lightness. This color model takes in three parameters, just like RGB. Here, we use it to specify colors, where hue is the color itself, saturation is the amount of gray, and lightness represents the brightness of the color. HSL uses these three values to define a color, making it easier to adjust the hue, saturation, and lightness of a color.

Hue (The color) Hue is the actual color value for an angle (without the unit) on the color wheel. The hue value is between 0° to 360° representing the shade of color on the color wheel. All other hue falls in between these predefined hue values:

  • Red is represented as 0° and 360°
  • Yellow is represented as 60°
  • Green is represented as 120°
  • Cyan is represented as 180°
  • Blue is represented as 240°
  • Magneta is represented as 300°

Saturation (Intensity of the color) Saturation refers to the intensity of a color, which is the dominance of hue in the color. The value ranges from 0% to 100%, where 0% means a shade of gray - fully desaturated, while a saturation of 100% is a state of full saturation showing a vibrant color.

Lightness (How bright) It describes the level of brightness of a color. It ranges from 0% to 100%, where 0% represents a dark/black color, and 100% represents a light color.

Syntax:

.element {
  hsl(120, 100%, 50%);
}

The code above results in a shade of green, where the hue value of 120 represents a green hue on the color wheel, the saturation value of 100% means the color is fully saturated, and the lightness value of 50% represents a medium lightness level.

Here is an interactive demo of HSL:

In the iframe above, we created a color palette for the visual representation of the HSL model. The color palette, partitioned, is into ten segments showing the saturation and lightness of colors as we move the slider.

The Alpha Channel for HSL and RGB

The alpha channel refers to the transparency level of a color, where an alpha value of 1.0 represents a fully opaque color, and an alpha value of 0.0 represents a fully transparent color. With RGB, the RGBa color model extends the number of parameters by 1 - an additional value representing the alpha channel. The syntax for creating using RGBs is

RGBa(red value, green value, blue value, alpha channel);

Where red, green, and blue represent the intensity of the corresponding color channels, just like in the native RGB and alpha, the newly added value is between 0.0 and 1.0, which denotes the level of transparency. For example, the following code sets the background color of an element to a partially transparent red (Half-translucent red):

.element {
  background-color: RGBa(255, 0, 0, 0.5);
}

Similarly, the HSLA color model extends the HSL color model by adding an alpha channel to specify the level of transparency. We define the syntax of an HSLA color value in CSS as:

hsla(hue, saturation, lightness, alpha);

Where hue, saturation, and lightness are the same as in HSL, and alpha is a value between 0.0 and 1.0, representing the level of transparency. For example, the following code sets the text color of an element to transparent blue:

.element {
  color: hsla(240, 100%, 50%, 0);
}

Alternatively, RGBa and HSLA can now be defined in a more expressive manner using the RGB function. In CSS Color Module Level 4, the HSLA (Hue, Saturation, Lightness, and Alpha) and RGBa (Red, Green, Blue, and Alpha) color models extend to allow for a more flexible and expressive way of defining colors.

One of the key features of CSS Color Module Level 4 is the ability to leave space between parameter values in the HSLA and RGBA color models. It means that developers can specify color values using commas and other separators between the parameters. It is a more human-readable syntax and makes it easier for developers to quickly change color values without having concern for syntax errors. In other to use this new format, leave a space between the parameters and add a forward slash before the last parameter, which is the alpha channel.

For example, the following code specifies a color in HSLA format with a hue of 120, a saturation of 60%, a lightness of 50%, and an alpha value of 0.5

.element {
  color: hsl(120 60% 50% / 0.5);
}

.element {
  color: rgb(165 0 0 / 0.4);
}

The CSS Color Module Level 4 provides a more flexible and expressive way of defining colors.

A comparison between Color keyword, RGB, and HSL - when one should be used over the other.

When it comes to defining colors in CSS, there are several options available to web developers: color keyword, RGB, and HSL, to mention a few. Each method has its benefits and disadvantages, and using one over another solely depends on the specific use case and your personal preference.

Comparison KeywordColor Keyword or Named ColorRGBHSL
DefinitionColor keywords are predefined color names in CSS, such as red, blue, green, etc.RGB (Red, Green, Blue) is a color model that combines red, green, and blue light to create a range of colors.HSL (Hue Saturation Lightness) is a color model that uses hue, saturation, and lightness to create colors.
Syntaxcolor:red; color:#F00;color:rgb(255,0,0); color:rgba(255,0,0,1);color:hsl(0,100%,50%); color:hsla(0,100%,50%,1);
Color RangeLimited to 147 named colorsWide range of colorsWide range of colors
Color AdjustmentSimple to use, but limited in terms of color optionsWide range of color options with fine-tuned control over the red, green, and blue componentsOffers a more intuitive way of defining colors, and control over the hue, saturation, and lightness values
UsageWhen a specific color is needed, and the color options are limitedWhen fine-tuned control over the colors is neededWhen defining colors in a more intuitive way is desired, and the color range is sufficient

Browser Support

Modern browsers like Google Chrome, Mozilla Firefox, Apple Safari, and Microsoft Edge support most color schemes. Older versions of Internet Explorer might be the only exception because they might not fully support some of the most recent color schemes, including RGBa and HSLa. The previous color techniques(hex values, named colors) are still usable in these circumstances and are well-supported even by outdated browsers. Testing your designs in multiple browsers is always a good idea to ensure they display as intended.

Other Color Alternatives

Besides the methods discussed above, there are several other color models by which we can define colors in CSS. These models include:

  • HWB (Hue-Whiteness-Blackness) color model: we use the HWB color model in creating colors with an emphasis on hue, whiteness, and blackness. It is useful when creating color schemes that are easy to read and have pleasant contrast. HTML does not support this color type.
  • CMYK (Cyan-Magenta-Yellow-Black) color model: The CMYK color model is used in the printing industry and is based on subtractive color mixing. We use it to represent colors based on the amount of cyan, magenta, yellow, and black ink required to produce a particular color. HTML does not support this color model.
  • LAB (Luminance-Achromatic-Chromatic) color model: We use the LAB color model in the image and video processing. It is generated based on human color perception. It represents colors by their luminance, chromaticity, and hue. The LAB color model is useful for color correction and color management.

Resources

For more understanding of the subject discussed, you can use these websites.

Conclusion

This article explores various color models and their representation, as well as the pros and cons of each. We delve into five commonly used methods for defining colors in CSS. When choosing a color model, it is important to consider your specific needs and personal preference.

Feel free to leave any comments or questions below. If you found this article informative, please share it with your network. Thank you.

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs and track user frustrations. Get complete visibility into your frontend with OpenReplay, the most advanced open-source session replay tool for developers.

OpenReplay