Make css variables bleed to children components

497 views Asked by At

I am using Polymer 2 to build a library of components, but I am having issues with css variables in browsers other than Chrome.

I have a wrapper component (x-page) and it has a theme property that can be either light or dark. My css looks similar to this:

:host([light]) {
    ---color-1: rgb(200,200,200);
    ---color-2: rgb(210,210,210);
}
:host([dark]) {
    ---color-1: rgb(10,10,10);
    ---color-2: rgb(20,20,20);
}

I now want to use these variables in all components inside this wrapper (not only directly slotted, all of them including their shadow-root.

In Chrome this works fine, as the children will read the variables from the wrapper, but in other browsers it doesn't seem to work even though I am using the apply-shim polyfill and tried with the custom-styles as well.

I appreciate your help :)

1

There are 1 answers

0
Supersharp On

In order that CSS styles can be applied with the Shadow DOM polyfill, at first you must prepare the <template> you append to the shadow root with the ShadyCSS.prepareTemplate() function, as explained in the ShadyCSS polyfill page:

ShadyCSS.prepareTemplate( template1, 'x-page' )

Example:

ShadyCSS.prepareTemplate( template1, 'x-page' )
class XPage extends HTMLElement {
    constructor() {
        super()
        this.attachShadow( { mode: "open" } )
            .appendChild( template1.content.cloneNode( true ) )
    }
}
customElements.define( 'x-page', XPage )
<script src="https://rawgit.com/webcomponents/webcomponentsjs/master/webcomponents-bundle.js"></script>

<template id="template1">
    <style>
        :host([light]) {
            ---color-1: red;
            ---color-2: pink;
        }
        :host([dark]) {
            ---color-1: yellow;
            ---color-2: black;
        }
        span { 
            color: var(---color-1);
            background-color: var(---color-2);
        }
    </style>
    <span><slot></slot></span>
</template>

<x-page light>Light</x-page>
<x-page dark>Dark</x-page>