CSS Variables and Custom Properties

CSS Variables, also known as Custom Properties, have revolutionized how developers write CSS, making it easier to manage and reuse values throughout a project. These variables provide a dynamic and flexible way to define and maintain consistent styles, reduce code repetition, and allow for more powerful theming.


1. What Are CSS Variables?

CSS Variables allow you to store values that can be reused across your CSS. This means that instead of hardcoding the same values repeatedly (like colors, fonts, or spacing), you define a variable once and use it anywhere in your stylesheet.

A custom property in CSS is defined using two dashes (--) followed by the variable name, and it’s applied using the var() function.

Example of Defining and Using CSS Variables:

				
					:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --padding: 10px;
}

button {
  background-color: var(--primary-color);
  padding: var(--padding);
  color: white;
}

.card {
  border: 1px solid var(--secondary-color);
  padding: var(--padding);
}

				
			

In this example:

  • --primary-color and --secondary-color store the main color schemes.
  • --padding is used to define a consistent padding for buttons and card elements.

By using variables, you ensure consistent styling across your website and make it easier to update the values in a single location rather than hunting through multiple CSS rules.


2. Why Use CSS Variables?

There are several advantages to using CSS variables over traditional methods of styling:

1. Reusability and Consistency

CSS Variables allow you to reuse the same values across your styles, ensuring consistency. For example, using the same color across different elements is easier when you define it as a variable.

2. Easy Maintenance

Instead of manually changing values in multiple locations, you can update a variable in one place, and the changes will automatically apply wherever the variable is used. This significantly reduces the chance of errors and simplifies your CSS maintenance.

3. Dynamic Styling

CSS Variables can be updated dynamically with JavaScript. This makes it possible to create interactive web pages where the styles can be adjusted based on user actions or preferences (e.g., switching themes).

4. Improved Theming

CSS Variables are extremely useful for theming. You can easily switch between dark and light themes by changing the values of your custom properties without having to rewrite your entire stylesheet.


3. Defining CSS Variables

CSS Variables are typically defined within the :root pseudo-class. The :root pseudo-class targets the highest-level element in the document, making the variables available globally across the entire stylesheet.

				
					:root {
  --main-bg-color: #f0f0f0;
  --font-size: 16px;
}

				
			

  • You can also define variables at a more local scope, such as within a specific class, but this will limit their availability to that class and its children.

  • 4. Using CSS Variables with var()

    To use a CSS Variable, the var() function is employed. This function takes the variable name and can also include a fallback value.

    				
    					body {
      background-color: var(--main-bg-color, #ffffff);
      font-size: var(--font-size, 14px);
    }
    
    				
    			

    In this case:

    • var(--main-bg-color) retrieves the value of --main-bg-color, defaulting to #ffffff if it's not defined.
    • var(--font-size) retrieves the --font-size, with a fallback of 14px if not set.


    5. Local and Global Scope for CSS Variables

    Variables can be scoped to specific elements, meaning that they can have different values in different contexts.

    Example:

    				
    					:root {
      --primary-color: #3498db;
    }
    
    .section {
      --primary-color: #e74c3c;
    }
    
    .header {
      background-color: var(--primary-color); /* Uses the global value */
    }
    
    .section .card {
      background-color: var(--primary-color); /* Uses the local value */
    }
    
    				
    			

    In this example:

    • The --primary-color for the .header uses the globally defined value #3498db.
    • However, the .section .card uses the locally defined value #e74c3c.


    6. Inheritance of CSS Variables

    CSS Variables naturally inherit from their parent elements. This means that if a child element doesn’t have a custom property defined, it will inherit the value from its parent.

    Example:

    				
    					:root {
      --font-color: black;
    }
    
    .parent {
      --font-color: blue;
    }
    
    .child {
      color: var(--font-color);
    }
    
    				
    			

    In this case, the child element will inherit the --font-color value from its parent and render its text in blue.


    7. CSS Variables in Media Queries

    One of the most powerful features of CSS Variables is their ability to work within media queries, allowing you to adjust variables based on different screen sizes.

    Example:

    				
    					:root {
      --font-size: 16px;
    }
    
    @media (max-width: 600px) {
      :root {
        --font-size: 14px;
      }
    }
    
    body {
      font-size: var(--font-size);
    }
    
    				
    			

    In this example:

    • The default font size is 16px for larger screens.
    • For screens smaller than 600px, the font size is reduced to 14px.

    This is incredibly useful for building responsive designs, as it allows you to dynamically adjust styles based on the user's device.


    8. Custom Properties with JavaScript

    CSS Variables can be manipulated dynamically through JavaScript, making it possible to update styles in real-time without altering the CSS file directly.

    Example of Changing Variables via JavaScript:

    				
    					<!DOCTYPE html>
    <html lang="en">
    <head><style>:root {
          --primary-color: #3498db;
        }
    
        body {
          background-color: var(--primary-color);
        }</style></head>
    <body>
      <button onclick="changeColor()">Change Color</button> <script defer src="data:text/javascript;base64,DQogICAgZnVuY3Rpb24gY2hhbmdlQ29sb3IoKSB7DQogICAgICBkb2N1bWVudC5kb2N1bWVudEVsZW1lbnQuc3R5bGUuc2V0UHJvcGVydHkoJy0tcHJpbWFyeS1jb2xvcicsICcjZTc0YzNjJyk7DQogICAgfQ0KICA="></script> </body>
    </html>
    
    				
    			

    In this example, clicking the button changes the --primary-color from blue to red dynamically, without refreshing the page or altering the CSS file.


    9. Best Practices for Using CSS Variables

    1. Use Meaningful Variable Names: Make sure your variable names are descriptive and easy to understand. Instead of using --color1, consider --primary-bg-color or --secondary-font-color.

    2. Define Variables in the :root Scope: If you intend to use a variable globally, define it in the :root pseudo-class for easier access throughout your CSS.

    3. Fallback Values: Always use fallback values in the var() function to ensure that styles render correctly if the variable is missing.

    4. Leverage for Theming: CSS Variables are ideal for creating multiple themes (e.g., light and dark themes) that can be switched with minimal changes to your CSS.


    10. Conclusion

    CSS Variables (Custom Properties) are a game-changer for web development, providing flexibility, reusability, and ease of maintenance for your styles. By defining values in one place and using them throughout your CSS, you can create cleaner, more efficient code, while also empowering dynamic and responsive design with JavaScript and media queries. Whether you're building simple web pages or complex applications, mastering CSS variables will significantly enhance your development workflow.

    ×