CSS Variables, also known as Custom Properties, are entities defined in CSS that store reusable values. They allow developers to centralize values like colors, fonts, and sizes, making CSS easier to maintain and update.
Syntax:
Declaring a Variable: CSS variables are prefixed with — and are usually defined in a global scope, such as the :root pseudo-class.
:root {
--primary-color: #3498db;
--font-size: 16px;
}
Using a Variable: To use a variable, the var() function is applied.
h1 {
color: var(--primary-color);
font-size: var(--font-size);
}
Fallback Value: You can add a fallback value in case the variable is not defined.
h1 {
color: var(--secondary-color, #333);
}
How to Update CSS Variables Dynamically with JavaScript
Define the Variable in CSS: Use :root (global scope) or a specific selector to declare your variable.
:root {
--primary-color: #3498db;
}
Access and Modify the Variable with JavaScript: Use the setProperty method on the style object of the desired element.
// Access the root element
const root = document.documentElement;
// Update the CSS variable
root.style.setProperty('--primary-color', '#ff0000');
Advantages of CSS Variables
Maintainability: Change the variable’s value in one place, and it updates across the entire project.
Consistency: Promotes consistent design by centralizing styles.
Theme Switching: Simplify creating themes (e.g., light mode, dark mode).
Dynamic Updates: JavaScript can modify variables in real-time for interactive effects.
CSS Variables– Interview Questions
Q 1: What are CSS variables?
Q 2: How do you declare a CSS variable?
" .
htmlspecialchars(
":root { --main-color: blue;} .
"",Q 3: How do you use a CSS variable?
Q 4: What is the advantage of CSS variables?
Q 5: Where are CSS variables commonly declared?
CSS Variables – Objective Questions (MCQs)
Q1. Which symbol is used to declare a CSS variable?
Q2. Which function is used to access CSS variables?
Q3. Where are global CSS variables defined?
Q4. Which is the correct CSS variable declaration?
Q5. How do you use a CSS variable?