Search code examples
javascriptcsswebpackweb-component

How do I access global css variable in webcomponent


I am using vanilla webcomponents and bundle with webpack.

In my components css I import the global css sheet with the @import declaration e.g

@import "../../style.css";

In style.css I have my variable defined e.g

:root {--variable: rgba(236, 236, 233, 0.0);}

From my component I can access other css declarations in the global style.css, but seemingly not the variable. e.g. this does not work for me in the components css:

background-color: var(--variable);

Neither does it seem to work when trying to access the variable from js e.g.

element.style.border = "2px solid var(--variable)";

Is this a limitation of the webcomponent technology / webpack or is there another way to access / define the global css variable so it is accessible inside the web component?


Solution

  • Ok.. Asking the question, inspired the solution.. Rubber Duck!

    I will leave the question, as I was not able to find a solution elsewhere and someone might have the same issue.

    I do not have the technical explanation (anybody who has is very welcome to elaborate), but defining global variables for access in webcomponents in a global stylesheet, should be inside the :host pseudo class and not in :root as per the documentation for global properties.

    This will work:

    :host {--variable: rgba(236, 236, 233, 0.0);}
    

    Or at least: it works for me ;)