2

First of all if you read this question and I did have any misunderstandings of how css works please let me know

I'm trying to add some global variables to my stylesheets and I want to do it with javascript (I thought there may be a way to use global variables without importing a css file containing those variables in each css file I'm creating):

let cssContent = `:root{ --mainColor:"#333";}

First I tried to create a new stylesheet file and put cssContent in there:

var blob = new Blob([cssContent]);
var url = URL.createObjectURL(blob);

var cssElement = document.createElement('link');
cssElement.setAttribute('rel', 'stylesheet');
cssElement.setAttribute('type', 'text/css');
cssElement.setAttribute('href', url);

Then to add this stylesheet to head, first I removed all exsisting stylesheets, add cssElement and then all the other removed stylesheets so the cssElement be the first stylesheet in head element.

var cssElements = Array.from(document.head.getElementsByTagName('link'))
                       .filter(link => link.getAttribute('rel') == 'stylesheet');
if (cssElements && cssElements.length > 0) {
       cssElements.forEach(cssEl => {
         document.head.removeChild(cssEl)
       });

The behavior of removing and adding stylesheets works fine enter image description here enter image description here enter image description here

But the :root element goes after the defined rule for body and does not apply:

enter image description here

Then I tried to add this variables to each css file instead of creating new one:

 for (let index = 0; index < document.styleSheets.length; index++) {
        document.styleSheets[index].insertRule(cssContent, 0);
      }

Again same thing happened to previous approach, happens here too:

enter image description here

At last I tried to add this variables to each rule, but I couldn't find an approach

Is there any way to do this?

2
  • Remove the quotes from around #333 Commented Jan 21, 2022 at 17:13
  • @AHaworth wow! how silly I am, I did remove the quote and It works fine now thanks Commented Jan 21, 2022 at 17:15

1 Answer 1

1

you can use these three:

document.documentElement.style.setProperty("--mainColor", "#333");

Element.setAttribute()

OR

document.documentElement.style.cssText = "--mainColor: #333";

Document.documentElement

OR

document.documentElement.setAttribute("style", "--mainColor: #333");

CSSStyleDeclaration.setProperty()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.