I have had the opportunity to edit over a lot of the new color entries coming to the CSS-Tricks Almanac. We’ve already published several with more on the way, including a complete guide on color functions:
- color()
- hsl()
- lab()
- lch()
- oklab()
- oklch()
- rgb()
And I must admit: I didn’t know a lot about color in CSS (I still usedrgb(), which apparently isn’t what cool people do anymore), so it has been a fun learning experience. One of the things I noticed while trying to keep up with all this new information was how long the glossary of color goes, especially the“color”concepts. There are “color spaces,” “color models,” “color gamuts,” and basically a “color” something for everything.
They are all somewhat related, and it can get confusing as you dig into using color in CSS, especially the new color functions that have been shipped lately, like contrast-color() and color-mix(). Hence, I wanted to make the glossary I wish I had when I was hearing for the first time about each concept, and that anyone can check whenever they forget what a specific “color” thing is.
As a disclaimer, I am not trying to explain color, or specifically, color reproduction, in this post; that would probably be impossible for a mortal like me. Instead, I want to give you a big enough picture for some technicalities behind color in CSS, such that you feel confident using functions likelab()oroklch()while also understanding what makes them special.
What’s a color?
Let’s slow down first. In order to understandeverythingincolor, we first need to understand thecolorineverything.
While it’s useful to think about an object being a certain color (watch out for theredcar, or cut thewhitecable!), color isn’t a physical property of objects, or even a tangible thing. Yes, we can characterizelightas the main cause of color1, but it isn’t until visible light enters our eyes and is interpreted by our brains that we perceive a color. As said byElle Stone:
Light waves are out there in the world, but color happens in the interaction between light waves and the eye, brain, and mind.
Even if color isn’t a physical thing, we still want to replicate it as reliably as possible, especially in the digital era. If we take a photo of a beautiful bouquet of lilies (like the one on my desk) and then display it on a screen, we expect to see the same colors in both the image and reality. However, “reality” here is a misleading term since, once again, therealityof color depends on the viewer. To solve this, we need to understand how light wavelengths (something measurable and replicable) create different color responses in viewers (something not so measurable).
Luckily, this task was already carried out 95 years ago by the International Commission on Illumination (CIE, by its French name). I wish I could get into the details of the experiment, but we haven’t gotten into our first color thingie yet. What’s important is that from these measurements, the CIE was able to map all the colors visible to the average human (in the experiment) to light wavelengths and describe them with only three values.
Initially, those three primary values corresponded to the red, green, and blue wavelengths used in the experiment, and they made up the CIERGBColor Space, but researchers noticed that some colors required a negative wavelength2to represent a visible color. To avoid that, a series of transformations were performed on the original CIERGB and the resulting color space was called CIEXYZ.
This new color space also has three values, X and Z represent the chromaticity of a color, while Y represents its luminance. Since it has three axes, it makes a 3D shape, but if we slice it such that its luminance is the same, we get all the visible colors for a given luminance in a figure you have probably seen before.
This is called thexy chromaticity diagramand holds all the colors visible by the average human eye (based on the average viewer in the CIE 1931 experiment). Colors inside the shape are considered real, while those outside are deemed imaginary.
Color Spaces
The purpose of the last explanation was to reach the CIEXYZColor Spaceconcept, but what exactly is a “color space”? And why is the CIEXYZColor Spaceso important?
The CIEXYZ Color Space is a mapping from all the colors visible by the average human eye into a 3D coordinate system, so we only need three values to define a color. Then, acolor space can be thought of as a general mapping of color, with no need to include every visible color, and it is usually defined through three values as well.
RGB Color Spaces
The most well-known color spaces are the RGB color spaces (note the plural). As you may guess from the name, here we only need the amount of red, green, and blue to describe a color. And to describe an RGB color space, we only need to define its “reddest”, “greenest”, and “bluest” values3. If we use coordinates going from 0 to 1 to define a color in the RGB color space, then:
- (1, 0, 0)means the reddest color.
- (0, 1, 0)means the greenest color.
- (0, 0, 1)means the bluest color.
However, “reddest”, “bluest”, and “greenest” are only arbitrary descriptions of color. What makes a color the “bluest” is up to each person. For example, which of the following colors do you think is the bluest?
As you can guess, something like “bluest” is an appalling description. Luckily, we just have to look back at the CIEXYZ color space — it’s pretty useful! Here, we can define what we consider the reddest, greenest, and bluest colors just as coordinates inside the xy chromaticity diagram. That’s all it takes to create an RGB color space, and why there are so many!
In CSS, the most used color space is the standard RGB (sRGB) color space, which, as you can see in the last image, leaves a lot of colors out. However, in CSS, we can use modern RGB color spaces with a lot more colors through thecolor()function, such asdisplay-p3,prophoto-rgb, andrec2020.
Notice how the ProPhoto RGB color space goes out of the visible color. This is okay. Colors outside are clamped; they aren’t new or invisible colors.
In CSS, besides sRGB, we have two more color spaces: the CIELAB color space and the Oklab color space. Luckily, once we understood what the CIEXYZ color space is, then these two should be simpler to understand. Let’s dig into that next.
CIELAB and Oklab Color Spaces
As we saw before, the sRGB color space lacks many of the colors visible by the average human eye. And as modern screens got better at displaying more colors, CSS needed to adopt newer color spaces to fully take advantage of those newer displays. That wasn’t the only problem with sRGB — it also lacks perceptual uniformity, meaning that changes in the color’s chromaticity also change its perceived lightness. Check, for example, thisdemo by Adam Argyle:
Created in 1976 by the CIE, CIELAB, derived from CIEXYZ, also encompasses all the colors visible by the human eye. It works with three coordinates: Lfor perceptual lightness, afor the amount of red-green, and b* for the amount of yellow-blue in the color.
It has a way better perceptual uniformity than sRGB, but it still isn’t completely uniform, especially in gradients involving blue. For example, in the following white-to-blue gradient, CIELAB shifts towards purple.
As a final improvement,Bj?rn Ottossoncame up with the Oklab color space, which also holds all colors visible by the human eye while keeping a better perceptual uniformity. Oklab also uses the threeL*a*b*coordinates. Thanks to all these improvements, it is the color space I try to use the most lately.
Color Models
When I was learning about these concepts, my biggest challenge after understanding color spaces was not getting them confused with color models and color gamuts. These two concepts, while complementary and closely related to color spaces, aren’t the same, so they are a common pitfall when learning about color.
A color model refers to the mathematical description of color through tuples of numbers, usually involving three numbers, but these values don’t give us an exact color until we pair them with a color space. For example, you know that in the RGB color model, we define color through three values: red, green, and blue. However, it isn’t until we match it to an RGB color space (e.g., sRGB withdisplay-p3) that we have a color. In this sense, a color space can have several color models, like sRGB, which uses RGB, HSL, and HWB. At the same time, a color model can be used in several color spaces.
I found plenty of articles and tutorials where “color spaces” and “color models” were used interchangeably. And some places were they had a different definition of color spaces and models than the one provided here. For example, Chrome’sHigh definition CSS color guidedefines CSS’s RGB and HSL as different color spaces, while MDN’sColor Space entrydoes define RGB and HSL as part of the sRGB color space.
Personally, in CSS, I find it easier to understand the idea of RGB, HSL and HWB as different models to access the sRGB color space.
Color Gamuts
A color gamut is more straightforward to explain. You may have noticed how we have talked about a color space having more colors than another, but it would be more correct to say it hasa “wider” gamut, since a color gamut is therange of colors available in a color space. However, a color gamut isn’t only restricted by color space boundaries, but also by physical limitations. For example, an older screen may decrease the color gamut since it isn’t able to display each color available in a given color space. In this case where a color can’t be represented (due to physical limitation or being outside the color space itself), it’s said to be “out of gamut”.
Color Functions
In CSS, the only color space available used to be sRGB. Nowadays, we can work with a lot of modern color spaces through their respective color functions. As a quick reference, each of the color spaces in CSS uses the following functions:
- sRGB:We can work in sRGB using the ol’ hexadecimal notation, named colors, and thergb(),rgba(),hsl(),hsla()andhwb()functions.
- CIELAB:Here we have thelab()for Cartesian coordinates andlch()for polar coordinates.
- Oklab:Similar to CIELAB, we haveoklab()for Cartesian coordinates andoklch()for polar coordinates.
- More through thecolor()andcolor-mix().Outside these three color spaces, we can use many more using thecolor()andcolor-mix()functions. Specifically, we can use the RGB color spaces:rgb-linear,display-p3,a98-rgb,prophoto-rgb,rec2020and the XYZ color space:xyz,xyz-d50, orxyz-d65.
TL;DR
- Color spaces are a mapping between available colors and a coordinate system. In CSS, we have three main color spaces: sRGB, CIELAB, and Oklab, but many more are accessible through thecolor()function.
- Color models define color with tuples of numbers, but they don’t give us information about the actual color until we pair them with a color space. For example, the RGB model doesn’t mean anything until we assign it an RGB color space.
- Most of the time, we want to talk about how many colors a color space holds, so we use the term color gamut for the task. However, a color gamut is also tied to the physical limitations of a camera/display. A color may be out-of-gamut, meaning it can’t be represented in a given color space.
- In CSS, we can access all these color spaces through color functions, of which there are many.
- The CIEXYZ color space is extremely useful to define other color spaces, describe their gamuts, and convert between them.
References
- Completely Painless Programmer’s Guide to XYZ, RGB, ICC, xyY, and TRCs(Elle Stone)
- Color Spaces (Bartosz Ciechanowski)
- The CIE XYZ and xyY Color Spaces(Douglas A. Kerr)
- From personal project to industry standard (Bj?rn Ottosson)
- High definition CSS color guide (Adam Argyle)
- Color Spaces: Explained from the Ground Up (Video Tech Explained)
- Color Space (MDN)
- What Makes a Color Space Well Behaved? (Elle Stone)
Footnotes
1 Light is the main cause of color, but color can be created by things other than light. For example, rubbing your closed eyes mechanically stimulates your retina, creating color in what’scalled phosphene. ??
2 If negative lightalso makes you scratch your head, and for more info on how the CIEXYZ color space was created, I highly recommend Douglas A. KerrThe CIE XYZ and xyY Color Spacespaper. ??
3We also need to define the darkest dark color (“black”) and the lightest light color (“white”). However, forwell-behavedcolor spaces, these two can be abstracted from the reddest, blues, and greenest colors. ??
The above is the detailed content of Color Everything in CSS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
