Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List CSS custom properties (CSS Variables)

I've set some CSS custom properties in my stylesheet:

:root {
    --bc: #fff;
    --bc-primary: #eee;
    --bc-secondary: #ddd;
}

I can retrieve them individually if I already know the name of the CSS variable like so:

console.log(getComputedStyle(document.body).getPropertyValue('--bc'));

// #fff

But if I wanted to pull a list of CSS variables and their values out, how would that be done?

like image 278
MorganR Avatar asked Aug 18 '17 18:08

MorganR


People also ask

What do CSS custom properties variables mean?

Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document.

Where do I define custom CSS properties?

The @property “at-rule” in CSS allows you to declare the type of a custom property, as well its as initial value and whether it inherits or not.

What CSS function is used to show the value of a custom property?

To define a custom property, use the name of your choice preceded by two dashes, for example: --my-property . Then you can use that value by calling it within the var() CSS function in place of providing a standard value.


2 Answers

One possible solution would be to parse the document.styleSheets, and then split the rules into properties/values

var allCSS = [].slice.call(document.styleSheets)
  .reduce(function(prev, styleSheet) {
    if (styleSheet.cssRules) {
      return prev + [].slice.call(styleSheet.cssRules)
        .reduce(function(prev, cssRule) {        
          if (cssRule.selectorText == ':root') {
            var css = cssRule.cssText.split('{');
            css = css[1].replace('}','').split(';');
            for (var i = 0; i < css.length; i++) {
              var prop = css[i].split(':');
              if (prop.length == 2 && prop[0].indexOf('--') == 1) {
                console.log('Property name: ', prop[0]);
                console.log('Property value:', prop[1]);
              }              
            }
          }
        }, '');
    }
  }, '');
:root {
    --bc: #fff;
    --bc-primary: #eee;
    --bc-secondary: #ddd;
}
like image 143
Asons Avatar answered Oct 29 '22 00:10

Asons


Based on LGSon's answer here is something similar but using map, filter, and flat to make it easier to read line by line.

const variables = [].slice.call(document.styleSheets)
    .map(styleSheet => [].slice.call(styleSheet.cssRules))
    .flat()
    .filter(cssRule => cssRule.selectorText === ':root')
    .map(cssRule => cssRule.cssText.split('{')[1].split('}')[0].trim().split(';'))
    .flat()
    .filter(text => text !== "")
    .map(text => text.split(':'))
    .map(parts => ({key: parts[0].trim(), value: parts[1].trim() }))
;

console.log(variables);
:root {
    --foo: #fff;
    --bar: #aaa
}
like image 24
mvndaai Avatar answered Oct 29 '22 00:10

mvndaai