CSS Variable Naming: Best Practices and Approaches
Tags: css, webdev, beginners, frontend
Published: 2024-07-10 10:06:22

Recently, while browsing the internet, like any good front-end developer, I wanted to "steal" the color palette of a site. So, I opened the inspector to copy the hexadecimal values of the colors and came across an unusual surprise: the CSS variables were named inconsistently.
<br><br>


<div style="display: flex; justify-content: space-between;">
<figure style="width: 48%; margin-right: 2%;"> 
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y26m14p3n9phpztltqt1.png" alt="css inconsistency names" style="width: 48%; margin-right: 2%;"/>

  <figcaption>I swear, it's not a meme.</figcaption>
</figure>


<br><br>
As you can see, the variable values did not match their names, which is a classic example of "naming inconsistency". It is crucial to avoid this in your codebase.

Naming CSS variables is essential for the organization, readability, and maintenance of the code in front-end projects. Despite seeming trivial, many companies still do not adopt a naming standard.

This article explores various approaches to naming CSS variables, highlighting the importance of semantic choices and consistent practices. If you don't know how to declare variables yet, I recommend you first read <a target="_blank" rel="noopener noreferrer" href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties">this article on MDN Web Docs</a>, and then come back here so we can talk about the various possible approaches.

<br><br>

## Table of Contents
<ul>
    <li>
        <a href="#why-use-variables">Why Use CSS Variables?</a>
    </li>
    <li>
        <a href="#benefits">Benefits of CSS Variables</a>
    </li>
    <li>
        <a href="#approaches">Approaches to Naming CSS Variables</a>
    </li>
    <li>
        <a href="#colors">Color-Based Naming</a>
    </li>
    <li>
        <a href="#semantic">Semantic Naming</a>
    </li>
    <li>
        <a href="#combination">Combination of Semantic and Color Names</a>
    </li>
    <li>
        <a href="#context">Contextual Naming</a>
    </li>
    <li>
        <a href="#scope">Scope-Based Naming</a>
    </li>
    <li>
        <a href="#components">Component-Based Naming</a>
    </li>
    <li>
        <a href="#type-value">Type-Based Naming</a>
    </li>
    <li>
        <a href="#theme">Theme-Based Naming</a>
    </li>
    <li>
        <a href="#tools">Linting Tools for CSS Variables</a>
    </li>
    <li>
        <a href="#conclusion">Conclusion</a>
    </li>
</ul>

<br><br>

### Why Use CSS Variables? <a id="why-use-variables" href="#why-use-variables">&#128279;</a>

According to CSS Tricks, CSS variables (custom properties) provide flexibility and power to CSS, allowing for the creation of dynamic themes and real-time style adjustments. Jonathan Harrell highlights that CSS variables are native, dynamic, and can be redefined within media queries, working in any CSS context, whether preprocessed or not.
<br><br>

### Benefits of CSS Variables <a id="benefits" href="#benefits">&#128279;</a>

- **Reuse:** Enable consistent use of values throughout the project.
- **Maintenance:** Simplifies style updates by changing values in one place.
- **Readability:** Meaningful names make the code easier to understand and maintain.

### Approaches to Naming CSS Variables <a id="approaches" href="#approaches">&#128279;</a>

**1. Color-Based Naming** <a id="colors" href="#colors">&#128279;</a> 

Naming CSS variables based on colors is a straightforward approach. This technique is useful for small projects or when colors have limited use, but care must be taken with potential maintenance issues. I'm mentioning this approach here, but I don't recommend using it.

```css
:root {
  --blue: #4267b2;
  --indigo: #3b2614;
  --purple: #754218;
  --pink: #f1ece7;
  --red: #b50000;
  --orange: #dc3545;
  --yellow: #f2b300;
  --green: #009733;
}
```
<br>
**Advantages:**

- **Immediate clarity:** Makes it easy to identify the exact color.
- **Simplicity:** Easy to implement.

**Disadvantages:**

- **Limited semantics:** Does not indicate the purpose of the color.
- **Reuse:** Can be confusing in larger projects with multiple usage contexts.
- **Maintenance:** Changing a color can break semantic consistency.

**2. Semantic Naming** <a id="semantic" href="#semantic">🔗</a>

Naming variables based on their purpose or usage context improves code understanding.

```css
:root {
  --primary-color: #4267b2;
  --secondary-color: #3b2614;
  --accent-color: #754218;
  --background-color: #f1ece7;
  --error-color: #b50000;
  --warning-color: #dc3545;
  --info-color: #f2b300;
  --success-color: #009733;
}
```
<br>
**Advantages:**

- **Semantic clarity:** Indicates the purpose or context of the color.
- **Ease of maintenance:** Simple to update and reuse.
- **Theming support:** Easy implementation of different themes.
- **Consistency:** Facilitates team collaboration.

**Disadvantages:**

- **Abstraction:** May require more effort to map names to specific colors.
- **Learning curve:** Can be challenging for new developers.

**3. Combination of Semantic and Color Names** <a id="combination" href="#combination">🔗</a>

Combines semantics with color description, providing clarity and context.

```css
:root {
  --primary-blue: #4267b2;
  --secondary-brown: #3b2614;
  --accent-purple: #754218;
  --background-pink: #f1ece7;
  --error-red: #b50000;
  --warning-orange: #dc3545;
  --info-yellow: #f2b300;
  --success-green: #009733;
}
```
<br>
**Advantages:**

- **Detailing:** Combines immediate clarity with semantic context.
- **Additional context:** Facilitates understanding and maintenance.

**Disadvantages:**

- **Verbosity:** Can result in longer, more verbose names.

**4. Contextual Naming** <a id="context" href="#context">🔗</a>
Variables are named according to their usage context.

```css

:root {
  --header-background: #333;
  --header-color: #fff;
  --footer-background: #222;
  --footer-color: #ccc;
}

.header {
  background-color: var(--header-background);
  color: var(--header-color);
}

.footer {
  background-color: var(--footer-background);
  color: var(--footer-color);
}
```
<br>
**Advantages:**

- **Contextual clarity:** Makes it easy to identify the purpose of variables in specific layout parts.
- Avoids conflicts:** Useful in large projects with multiple components.

**Disadvantages:**

- **Potential repetition:** There may be redundancy of variables for different contexts.

**5. Scope-Based Naming** <a id="scope" href="#scope">🔗</a>
Variables are named to reflect the specific scope where they will be used. This can help avoid naming conflicts in large projects.

```css

:root {
  --button-primary-bg: #007bff;
  --button-primary-color: #fff;
  --button-secondary-bg: #6c757d;
  --button-secondary-color: #fff;
}

.button-primary {
  background-color: var(--button-primary-bg);
  color: var(--button-primary-color);
}

.button-secondary {
  background-color: var(--button-secondary-bg);
  color: var(--button-secondary-color);
}
```
<br>
**Advantages:**

- **Avoids conflicts:** Reduces the chance of name collisions in large codebases.
- **Clear scope:** Facilitates code maintenance and readability.

**Disadvantages:**

- **Complexity:** Can add complexity when managing many different scopes.

**6. Component-Based Naming** <a id="components" href="#components">🔗</a>
Variables are named according to specific interface components. This is common in methodologies like BEM (Block Element Modifier).

```css
:root {
  --card-background: #fff;
  --card-border: 1px solid #ddd;
  --card-title-color: #333;
}

.card {
  background-color: var(--card-background);
  border: var(--card-border);
}

.card-title {
  color: var(--card-title-color);
}
```
<br>
**Advantages:**

- **Component clarity:** Makes it easy to identify variables related to specific components.
- **Modularity:** Facilitates reuse of styles in different parts of the project.

**Disadvantages:**

- **Maintenance:** Can be more difficult to maintain consistency in very large projects.

**7. Type-Based Naming** <a id="type-value" href="#type-value">🔗</a>
Variables are named to reflect the type of value they represent. This is useful for maintaining consistency throughout the project.

```css
:root {
  --color-primary: #3498db;
  --color-secondary: #2ecc71;
  --font-size-small: 12px;
  --font-size-medium: 16px;
  --font-size-large: 24px;
  --spacing-small: 8px;
  --spacing-medium: 16px;
  --spacing-large: 32px;
}

.text-primary {
  color: var(--color-primary);
}

.text-secondary {
  color: var(--color-secondary);
}

.small-text {
  font-size: var(--font-size-small);
}

.medium-text {
  font-size: var(--font-size-medium);
}

.large-text {
  font-size: var(--font-size-large);
}

.margin-small {
  margin: var(--spacing-small);
}

.margin-medium {
  margin: var(--spacing-medium);
}

.margin-large {
  margin: var(--spacing-large);
}
```
<br>
**Advantages:**

- **Consistency:** Facilitates maintenance and readability by using a clear convention for types of values.
- **Modularity:** Facilitates reuse of variables in different contexts.

**Disadvantages:**

- **Verbosity:** Can result in long names.

### 8. Theme-Based Naming <a id="theme" href="#theme">🔗</a>
Variables are named to reflect different themes or modes (such as light mode and dark mode).

```css
:root {
  --color-background-light: #ffffff;
  --color-background-dark: #000000;
  --color-text-light: #000000;
  --color-text-dark: #ffffff;
}

.light-theme {
  background-color: var(--color-background-light);
  color: var(--color-text-light);
}

.dark-theme {
  background-color: var(--color-background-dark);
  color: var(--color-text-dark);
}
```
<br>
**Advantages:**

- **Flexibility:** Facilitates the creation and maintenance of different visual themes.
- **Consistency:** Variables can be easily swapped to change the theme.

**Disadvantages:**

- **Complexity:** Managing multiple themes can add complexity to the project.

### Linting Tools for CSS Variables <a id="tools" href="#tools">🔗</a>
Linting tools can help ensure that variables follow specific naming conventions, promoting consistency in the code. Examples of tools include:

<a href="https://stylelint.io/" target="_blank" rel="noopener noreferrer">Stylelint</a>: A modern, flexible linter for CSS that can be configured to check variable consistency.
<br>
<a href="https://postcss.org/" target="_blank" rel="noopener noreferrer">PostCSS</a>: A tool that transforms CSS with plugins, including variable checks.
<br>
<a href="https://github.com/CSSLint/csslint" target="_blank" rel="noopener noreferrer">CSS Linter</a>: A specific tool to ensure correct and consistent use of CSS variables.
<br><br>
**Conclusion** <a id="conclusion" href="#conclusion">🔗</a>

These approaches and practices can help ensure that the use of CSS variables in your projects is efficient, organized, and easy to maintain. The right approach depends on your project's needs and scale, as well as your development team's preferences and practices.

**Credits** <a id="credits" href="#credits">🔗</a>

This article was inspired by personal experiences and studies from various reference sources, including CSS Tricks and the works of <a target="_blank" rel="noopener noreferrer" href="https://www.jonathan-harrell.com/about/">Jonathan Harrell</a>.