SmartCodingTips

CSS Variables

CSS Variables (also called custom properties) allow you to store reusable values — such as colors, font sizes, or spacing — in a single place. This improves consistency and maintainability in your stylesheets.

1. Declaring CSS Variables

CSS variables are defined inside a selector using the -- prefix. They are often placed inside the :root pseudo-class to make them globally accessible.


:root {
    --primary-color: #4f46e5;
    --secondary-color: #3b82f6;
    --font-size-lg: 18px;
}
            

2. Using CSS Variables

Use the var() function to apply the value of a variable.


body {
    background-color: var(--primary-color);
    font-size: var(--font-size-lg);
}

button {
    background-color: var(--secondary-color);
}
            

3. Local vs Global Scope

Variables defined in :root are global, but you can define them in any selector for local usage:


.card {
    --card-padding: 20px;
    padding: var(--card-padding);
}
            

4. Fallback Values

You can provide a fallback in case the variable is not defined:


h1 {
    color: var(--title-color, black);
}
            

5. Dynamic Themes

CSS variables are powerful for implementing themes. Change the variables at runtime using JavaScript or apply them conditionally via classes.


.theme-dark {
    --background: #1f2937;
    --text: #f9fafb;
}

body {
    background-color: var(--background);
    color: var(--text);
}
            

Conclusion

CSS Variables make your styles more organized, maintainable, and scalable. They're a must-know for modern CSS development and are supported in all major browsers.