-
Hajipur, Bihar, 844101
CSS Variables, also known as custom properties, are entities defined by authors that contain specific values to be reused throughout a document.
They help make styles more maintainable, reusable, and easier to update.
:root {
--main-color: #3498db;
--font-size: 18px;
}
h1 {
color: var(--main-color);
font-size: var(--font-size);
}
Variables start with --
Access them using var(--variable-name)
Declare them inside :root
for global access
:root {
--bg-color: #fff;
}
Accessible from anywhere in the CSS.
.card {
--padding: 20px;
padding: var(--padding);
}
Only accessible within .card
and its children.
color: var(--primary-color, blue);
If --primary-color
is not defined, blue will be used.
document.documentElement.style.setProperty('--main-color', 'red');
CSS variables are dynamic and can be changed via JavaScript at runtime.
Reusability
Centralized control
Easy theme management (light/dark modes)
JavaScript-friendly
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
.dark-theme {
--bg-color: #000000;
--text-color: #ffffff;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
Switch .dark-theme
class to activate dark mode.
Q1. Create a variable for primary color and apply it to headings.
Q2. Define a --radius
and use it for button border-radius.
Q3. Use --font-base
for font size of all paragraphs.
Q4. Add --box-shadow
for cards and apply it.
Q5. Define a fallback for an undefined variable.
Q6. Set --container-width
and use it in a .container
class.
Q7. Change --main-color
dynamically using JavaScript.
Q8. Create light and dark themes using CSS variables.
Q9. Apply --gap
between grid columns.
Q10. Make a reusable --transition-speed
variable and apply it to links.
Q1: What is the correct syntax for a CSS variable?
Q2: Which selector is typically used for global variables?
Q3: How do you use a CSS variable?
Q4: What is the fallback in this rule: color: var(--text, black);?
Q5: Where can local scoped CSS variables be defined?
Q6: Which of the following is NOT true about CSS variables?
Q7: What does setProperty('--main-color', 'red') do?
Q8: Which of these is a valid variable name?
Q9: Which of the following can use CSS variables?
Q10: Why are CSS variables better than hardcoded values?