SyntaxStudy
Sign Up
jQuery jQuery CSS Variables and Custom Properties
jQuery Advanced 6 min read

jQuery CSS Variables and Custom Properties

CSS custom properties (CSS variables) are a modern way to centralise design tokens like colours, spacing, and font sizes. Although jQuery predates their wide adoption, you can read and write CSS variables using a combination of .css() and native DOM APIs, keeping your jQuery code future-friendly.

Reading CSS Variables

jQuery's .css() does not natively support CSS custom property names that start with --. The reliable approach is getComputedStyle(element).getPropertyValue('--var-name') via the DOM, which you can call on the raw element from a jQuery object using index notation: el[0].

Writing CSS Variables

To update a CSS variable use the native element.style.setProperty('--var-name', value). Changing a custom property on :root (the html element) propagates the new value everywhere the variable is used, making it a powerful global theme switch.

  • Read: getComputedStyle($('#el')[0]).getPropertyValue('--primary')
  • Write: $('html')[0].style.setProperty('--primary', '#0074d9')
  • Theme toggle: update one variable on :root to retheme the whole page

This pattern is especially useful for dark-mode toggles — simply swap the value of a --bg and --text variable on the root element with a single button click.

Example
// Read a CSS custom property
var primary = getComputedStyle($('html')[0])
                  .getPropertyValue('--primary-color').trim();
console.log('Primary colour: ' + primary);

// Write a CSS custom property on :root
$('html')[0].style.setProperty('--primary-color', '#e74c3c');

// Dark-mode toggle
$('#theme-btn').on('click', function () {
    var root = $('html')[0];
    var isDark = root.getAttribute('data-theme') === 'dark';
    root.setAttribute('data-theme', isDark ? 'light' : 'dark');
    root.style.setProperty('--bg',   isDark ? '#fff'  : '#1a1a2e');
    root.style.setProperty('--text', isDark ? '#000'  : '#eee');
});
Pro Tip

Update CSS variables on the :root element to implement global theme changes with minimal JavaScript.