Using the currentColor CSS keyword

https://youtu.be/IbySLtF2XNU

I learnt about this CSS keyword via Glen Maddern's talk at Cold Front in Copenhagen, back in September, and I was super astonished I hadn't heard about it before! I guess I do too much JavaScript 😏

Anyway, it represents the current inherited color, so you can use it to create borders and backgrounds and things like that, matching the color of the element, but without actually writing it again! This can help in avoiding repetition and keeping the CSS more manageable, or in Glen's use case, in writing more responsive components.

Given this HTML code:


<p id="thing">hello <span>world</span></p>

and this CSS code:


#thing {
  color: blue;
  font-size: 3rem;
}

#thing span {
  padding: 3px;
  background-color: white;
  box-shadow: 0px 0px 20px currentColor;
}

the color for the box-shadow in the #thing span will be blue, because it uses currentColor, which at that point has inherited blue from #thing. If we change the color of #thing to something else, we do not need to update the code for #thing span. Beautiful!

You could even use CSS variables to set a global colour variable that is used in the document, and currentColor will inherit values set with var. For example:


body {
  --thecolor: red;
}

#thing {
  color: var(--thecolor);
  font-size: 3rem;
}

#thing span {
  padding: 3px;
  background-color: white;
  box-shadow: 0px 0px 20px currentColor;
}

... renders the text red, and the box shadow is red as well.

Fantastic!

Unfortunately it seems like calc() doesn't accept color units yet, which means we cannot do maths on the color values. Otherwise, we could do things such as what CSS pre-processors do, generating new colours using hsla functions, etc.