Skip to main content

CSS Variables and JavaScript

CSS Variables and JavaScript

CSS Variables, also known as custom properties, are a powerful feature that enables dynamic and reusable styling. Integrating CSS Variables with JavaScript opens up the possibility to manipulate styles programmatically, making your web applications more interactive and flexible.


01. What Are CSS Variables?

CSS Variables are user-defined properties that hold values for various CSS properties. They are declared with a -- prefix and can be used throughout the CSS styles. One of the main benefits of CSS Variables is that they can be overridden in different scopes, enabling dynamic theming and customization.

Example of defining a CSS variable:


:root {
  --primary-color: #3498db;
}

h1 {
  color: var(--primary-color);
}

02. Accessing and Manipulating CSS Variables with JavaScript

JavaScript can be used to access and modify CSS Variables dynamically, which allows developers to change styles on the fly based on user interaction or other factors.

1. Accessing CSS Variables in JavaScript

To access a CSS Variable in JavaScript, you need to query the style of an element and retrieve the variable using getComputedStyle().


const root = document.documentElement; // Access the :root element
const primaryColor = getComputedStyle(root).getPropertyValue('--primary-color');
console.log(primaryColor); // Logs the current value of --primary-color

2. Modifying CSS Variables with JavaScript

To modify a CSS variable dynamically, you can use the style.setProperty() method on an element’s style property. This method allows you to change the value of a custom property directly through JavaScript.


document.documentElement.style.setProperty('--primary-color', '#e74c3c');

The above code updates the value of --primary-color to #e74c3c in the entire document, making all elements that reference this variable reflect the change immediately.


03. Practical Applications of Using CSS Variables with JavaScript

There are several practical scenarios where you can benefit from integrating CSS Variables with JavaScript, such as implementing dynamic themes, real-time style updates, and interactive UI elements.

1. Dynamic Theming

CSS Variables enable the creation of dark/light themes or custom themes by dynamically updating variables with JavaScript. Here’s an example of switching between dark and light themes:


function toggleTheme() {
  const root = document.documentElement;
  const currentTheme = getComputedStyle(root).getPropertyValue('--background-color');

  if (currentTheme === 'rgb(255, 255, 255)') { // Light theme
    root.style.setProperty('--background-color', '#2c3e50');
    root.style.setProperty('--text-color', '#ecf0f1');
  } else { // Dark theme
    root.style.setProperty('--background-color', '#ffffff');
    root.style.setProperty('--text-color', '#2c3e50');
  }
}

In this example, the background and text color change based on the current theme, providing a seamless user experience.

2. Real-Time UI Adjustments

CSS Variables can be modified in response to user interactions to provide a more dynamic UI. For example, adjusting the size of an element based on user input:


document.querySelector('#slider').addEventListener('input', (e) => {
  const root = document.documentElement;
  const size = e.target.value;
  root.style.setProperty('--element-size', size + 'px');
});

In this example, the size of an element is dynamically adjusted as the user moves a slider, using a CSS variable to store and apply the new value.

3. Customizing Animations

CSS Variables can be used to control the speed, timing, or other parameters of animations in real-time. You can manipulate the value of a CSS variable that controls animation properties to modify the animation behavior.


document.querySelector('#speedControl').addEventListener('input', (e) => {
  const root = document.documentElement;
  const animationSpeed = e.target.value + 's'; // Get speed from input
  root.style.setProperty('--animation-duration', animationSpeed);
});

By updating the --animation-duration variable, the speed of the animations can be adjusted on the fly.


04. Best Practices for Using CSS Variables with JavaScript

  • Use Fallback Values: When modifying variables, make sure to provide fallback values in case JavaScript manipulation fails.
  • Limit Direct Manipulation: Avoid manipulating too many variables directly in JavaScript, as it may reduce the maintainability of the code.
  • Group Related Variables: Group related CSS variables together to make it easier to manage and update styles through JavaScript.
  • Use for Responsiveness: Use CSS Variables to adjust styles dynamically based on screen size or user preferences, improving user experience.

05. Browser Support

CSS Variables are supported by most modern browsers, but older versions of Internet Explorer and Safari may not fully support them. Be sure to test for compatibility and consider adding fallback styles when working with older browsers.

  • Google Chrome 49+
  • Mozilla Firefox 31+
  • Safari 9.1+
  • Microsoft Edge 15+
  • Opera 36+

06. Conclusion

CSS Variables provide a versatile and powerful method to manage styles dynamically, and when combined with JavaScript, they offer even greater flexibility in building interactive, real-time web applications. By understanding how to integrate these technologies, developers can create engaging and responsive user interfaces that adjust to various conditions or user preferences.


Additional Resources

Comments