CSS variables (custom properties) are incredibly powerful, and one of their best features is that they can be dynamically updated using JavaScript. This allows you to create interactive and responsive designs where styles adapt based on user interaction or other events.
How to Access and Modify CSS Variables with JavaScript
To modify CSS variables with JavaScript, follow these steps:
1. Access the Root Element
CSS variables are usually defined in the :root
selector. The document.documentElement
property represents the root <html>
element where global variables are defined.
2. Use setProperty()
to Change Variables
You can use the setProperty()
method to dynamically update the value of a CSS variable.
Basic Example
Here’s a simple example of changing the background color dynamically:
HTML:
<div class="container">
<button onclick="changeBackground()">Change Background</button>
</div>
CSS:
:root {
--background-color: #f8f9fa;
}
.container {
background-color: var(--background-color);
padding: 20px;
text-align: center;
}
JavaScript:
function changeBackground() {
document.documentElement.style.setProperty('--background-color', '#007bff');
}
In this example:
- The CSS variable
--background-color
is initially set to light gray (#f8f9fa
). - Clicking the button triggers the
changeBackground()
function, which updates--background-color
to blue (#007bff
).
Advanced Example: Real-Time Theme Switcher
Let’s create a light/dark theme switcher using CSS variables and JavaScript.
HTML:
<div class="theme-toggle">
<button onclick="toggleTheme()">Toggle Theme</button>
</div>
CSS:
:root {
--background-color: #ffffff;
--text-color: #000000;
}
body {
background-color: var(--background-color);
color: var(--text-color);
font-family: Arial, sans-serif;
padding: 20px;
transition: all 0.3s ease; /* Smooth transition */
}
JavaScript:
let isDarkMode = false;
function toggleTheme() {
if (isDarkMode) {
document.documentElement.style.setProperty('--background-color', '#ffffff');
document.documentElement.style.setProperty('--text-color', '#000000');
isDarkMode = false;
} else {
document.documentElement.style.setProperty('--background-color', '#000000');
document.documentElement.style.setProperty('--text-color', '#ffffff');
isDarkMode = true;
}
}
This example toggles between light and dark themes:
- On button click, the
toggleTheme()
function switches the values of--background-color
and--text-color
. - The smooth transition effect (
transition: all 0.3s ease
) makes the theme change visually appealing.
Changing Variables Based on User Input
You can dynamically change CSS variables based on user input, such as a color picker or slider.
Example: Color Picker
HTML:
<div class="color-picker">
<label for="color">Choose Background Color:</label>
<input type="color" id="color" onchange="changeColor(event)">
</div>
CSS:
:root {
--background-color: #ffffff;
}
body {
background-color: var(--background-color);
padding: 20px;
text-align: center;
}
JavaScript:
function changeColor(event) {
const newColor = event.target.value;
document.documentElement.style.setProperty('--background-color', newColor);
}
This example allows the user to select a background color using a color picker, and the CSS variable updates dynamically.
Responsive Design with Dynamic Variables
CSS variables can also be updated dynamically to adapt to the viewport size, user interaction, or other conditions.
Example: Dynamic Font Size Adjustment
HTML:
<div class="text-resize">
<p>Resize the font size using the slider below:</p>
<input type="range" min="12" max="48" value="16" onchange="resizeFont(event)">
</div>
CSS:
:root {
--font-size: 16px;
}
p {
font-size: var(--font-size);
transition: font-size 0.2s ease;
}
JavaScript:
function resizeFont(event) {
const newFontSize = event.target.value + 'px';
document.documentElement.style.setProperty('--font-size', newFontSize);
}
This example uses a slider to dynamically adjust the font size of the text.
Real-World Applications
- Theme Switchers: Toggle between light/dark or other themes dynamically.
- Interactive Components: Change button colors, backgrounds, or fonts based on user input.
- Accessibility Features: Adjust font size or spacing to improve readability.
- Dynamic Layouts: Modify margins, paddings, or grid sizes in real-time for responsive design.
Browser Compatibility
CSS variables and the setProperty()
method are supported in all modern browsers, including:
- Chrome
- Firefox
- Safari
- Edge
Note: CSS variables are not supported in Internet Explorer.
Best Practices
- Organize Variables in
:root
: Keep your variables centralized for easier management. - Use Fallback Values: Provide fallback values in
var()
to handle undefined variables. - Minimize JavaScript Usage: Use JavaScript only when dynamic updates are necessary.
- Optimize for Performance: Avoid unnecessary DOM manipulations in performance-critical applications.
Conclusion
Changing CSS variables with JavaScript opens the door to highly interactive and responsive web designs. Whether you’re building a theme switcher, allowing users to customize layouts, or creating dynamic animations, combining CSS variables with JavaScript makes your web applications more flexible and engaging.
For more web development tutorials, check out The Coding College and elevate your coding skills today!