Using currentColor in CSS

In CSS, colors do more than just make a page look nice — they help style and connect elements together. Besides the usual ways to write a color, there's also a special keyword called 'currentColor'. It adds some neat tricks you can use beyond just setting a color normally.

The Color data type

In CSS you give color to HTML elements by using the Color data type, which can be written in different formats. For example as named color ('mediumseagreen'), in hexadecimal format (#1b5ecd) or as color function (rgba(154, 37, 16, 1)). You can use it to style different properties of an HTML element.

div.warm {
    color: red;
    border: 1px solid #91251e;
    box-shadow: 0 4px 8px 5px rgb(145, 37, 30);
    background: hsla(24, 78%, 40%, 1.00);
}

The 'color' property is a bit special in the way that the child element(s) inherit that color value. So the text in a child element has the same color, by default.

The 'currentColor' keyword

We also have the option to use the currentColor keyword, which you can use for properties that accept the Color data type. This keyword allows us to get and use the value of the 'color' style property of the (parent) element.

Example 1: apply color to same element

In this example, the currentColor will have the same value as the 'color' property has.

<div class="colorful">Hello</div>
div.colorful {
    color: #842a96;
    border: 1px solid currentColor; /* The border color is also #842a96 */ 
}

Example 2: apply color to child element

In this example, the currentColor in the child element will have the same value as the 'color' property of the parent element.

<div class="parent">
    <p class="child">Hello</p>
</div>
div.parent {
    color: #276ac2;
}

p.child {
    background-color: currentColor; /* The background color is also #276ac2 */ 
}

Change fill color of an SVG

The currentColor keyword can also be applied to the 'fill' style property of an SVG element, since this property supports the Color data type. When used, the element's fill will inherit the color defined by its parent element's 'color' property.

This trick allows us to style text with SVG icons with the same color.

Below is an example showing how currentColor works when applied to the 'fill' property in an SVG element.

References

Color data type in MDN

CSS tricks - Cascading SVG Fill Color