Sunday, 7 March 2021

Javascript Properties in CSS

 Style LWC Component using javascript property values.


style.setProperty()


Using style.setProperty() to keep CSS Property Names Consistent in Javascript.


:host 


This allows you to select a custom element from inside its shadow DOM.



cssDemo.js 


import {LightningElement,api} from lwc';


export default class CssDemo extends LightningElement{

  @api backgroundColor;

  @api textColor;

  

  renderedCallback(){

    this.template.host.style.setProperty("--my-bg-color",this.backgroundColor);

this.template.host.style.setProperty("--my-text-color",this.textColor);

// base component style

this.template.host.style.setProperty("--sds-c-badge-color-background",this.backgroundColor);

this.template.host.style.setProperty("--sds-c-badge-text-color",this.textColor);

  }

  

}



cssDemo.css 


:host{

  --my-text-color : black;

  --my-bg-color : white;

}


.container{

  background : var(--my-bg-color);

  color      : var(--my-text-color);

}


.someOtherClass{

  border-color : var(--my-text-color);

}  


.slds-badge{

   background-color : var (--sds-c-badge-color-background,#ECEBEA);

   color : var(--sds-c-badge-text-color,#080707);

}