skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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 ;)


  2. Can you elaborate?

    CSS variables from Global CSS are available all the way down the DOM, including shadowDOM

    <style>
      :root {
        --var1: red;
      }
    
      body {
        --var2: gold;
      }
    </style>
    
    <my-component></my-component>
    
    <script>
      customElements.define("my-component", class extends HTMLElement {
        constructor() {
          super()
            .attachShadow({mode: "open"})
            .innerHTML = `<style>
                          :host{
                            display:block;
                            background: var(--var1);
                            color: var(--var2);
                          }
                          </style>
                          <h1>Hello Web Component World!</h1>`;
        }
      })
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search