1

I have notice that if I set variable in the CSS and then set them using the document:

document.documentElement.style.setProperty(var_name, val)

Then this change apply to all components that using variable with the same name.

Is that the expected result? Is there recommended way to set only the variable of the component in context?

can test it by simply create a component:

template:

 <template>
        <div class="test-style">
    
        </div>
    </template>

css:

.test-style{
    background-color: var(--testBGColor);
    width: 100px;
    height: 100px;
}

js:

import { LightningElement, api } from 'lwc';

export default class TestChildComponent extends LightningElement {
    @api
    get compcolor(){
        return this._compcolor;
    }
    set compcolor(value){
        this._compcolor = value;
        document.documentElement.style.setProperty('--testBGColor', this._compcolor);
    }
}

then create a parent component that use it few times with different parameter. Although setting different color for each instance, all will result with the same background color:

<template>
    <div style="display:flex;justify-content: space-between;">
        <c-test-child-component compcolor="#ff0000">

        </c-test-child-component>

        <c-test-child-component compcolor="#00ff00">

        </c-test-child-component>

        <c-test-child-component compcolor="#0000ff">

        </c-test-child-component>
    </div>
</template>

1 Answer 1

1

Yes, this is expected. document.documentElement.style is the global style sheet. You should not set variables at this level. Instead, use this.template.host.style:

this.template.host.style.setProperty('--testBGColor', this._compcolor);

You can also generally set a CSS property on a specific element (e.g. this.template.querySelector('.some-css-selector').style.setProperty(...) if you want to do this dynamically from outside the component.

Demo.

1
  • Thanks, works perfect with template.host.style
    – Liron C
    Apr 10, 2023 at 22:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .