Defining a Custom Property in CSS

To define a custom property, select a name and prefix it with two hyphens. Any alphanumeric character can be part of the name. Hyphen ( – ) and underscore ( _ ) characters are also allowed. A broad range of Unicode characters can be part of a custom property name. This includes emoji, but for the sake of clarity and readability, stick to alphanumeric names.

Here’s an example:

–primarycolor: #0ad0f9ff; /* RGB alpha hexadecimal color notation */

The — indicates to the CSS parser that this is a custom property. When used as a variable, the parsing engine replaces the property with its value.

Custom property names are case-sensitive. That means –primarycolor and — primarycolor are considered two distinct property names. That’s a departure from traditional CSS, in which property and value case don’t matter. It is, however, consistent with the rules for variable names in ECMAScript.

As with other properties, such as display or font , CSS custom properties must be defined within a declaration block. One common pattern is to define custom properties using the :root pseudo-element as a selector:

:root {

–primarycolor: #0ad0f9ff;

}

:root is a pseudo-element that refers to the root element of the document. For HTML documents, that’s the <html> element. For SVG documents, it’s the <svg> element. Using :root makes properties immediately available throughout the document.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *