Dmitry
Dmitry

Reputation: 101

How can I find what CSS variables are used in styles of a given element?

I have a color palette defined as CSS variables.

:root {
  --background-normal: #fffff;
  --text-normal: #212a32;
  --background-warning: #ff0000;
  --text-warning: #ffffff;
}

CSS classes for elements are using these variables.

#article-body {
   background-color: var(--background-normal);
   color: var(--text-normal);
}

Different classes are using different variables. What I need to be able to do is to analyse a certain element on a rendered page and tell which CSS variables it uses in its styles. For example: div#article-body uses variables background-normal and text-normal.

I can get computed styles for an element by using getComputedStyle but the returned styles have all CSS variables replaced with actual values.

Any ideas on how I can extract CSS with variable names in it?

Upvotes: 4

Views: 1153

Answers (1)

Dmitry
Dmitry

Reputation: 101

The only workaround that I found so far is to change each CSS variable and see if that change appears in any of the elements. Something like this:

var bodyStyles = window.getComputedStyle(document.body);
var check = "rgb(12, 34, 56)";
var vars = ["--background-normal", "--text-normal", "--background-warning", "--text-warning"];

function checkUsage (element, index, array) {
  var origValue = bodyStyles.getPropertyValue(element);
  document.body.style.setProperty(element, check);
  var found = false;
  $("#article-body *").each (function(index, el) {
    var allCSS = getComputedStyle(el).cssText;
    if (allCSS.indexOf(check) >= 0) {
        found = true;
    }
    });
  document.body.style.setProperty(element, origValue);
  if (found) console.log(element);
}

vars.forEach(checkUsage);

This works quite fast and you can't notice flickering due to color change. At least on a small amount of elements within the container. This method has a chance of false detection in case the original value of one of the CSS variables was the same as the check. That's acceptable in my case, but I wish there was a cleaner way.

Upvotes: 1

Related Questions