Tuesday 3 May 2022

Style in LWC

 Following are the ways we can apply in CSS in LWC.

1. Inline CCS

Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div
<template>
    <lightning-card title="Inline CSS">
        <div>
            <div style="color:green;font-size:10px;">This is inline Style div</div>
        </div>
    </lightning-card>
</template>

 2. External CSS
style can be applied to an elements such as h1, p,div span etc.
It can applied to class using "." notation. for example .user{}
It can also be applied to pseudo class.  for example .user:hover{}
Id locator is not being used in LWC to apply style

To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is externalCSS then file name should be "externalCSS .css"

<template>   
    <lightning-card title="External CSS">
        <div>
            <div class="externalDiv">This is External Style div</div>
            <p> This is a p Tag</p>
        </div>
    </lightning-card>
</template>

CSS File.
.externalDiv{
    background-color: yellow;
    color:blue;
    font-size:20px;
}
p{
    color:green;
    font: size 20px;
    border: 1px solid red;
}
.externalDiv:hover{
    background-color: white;
    color:red;
    font-size:50px;
}

3. Lightning Design System.
Its a salesforce standard style library.- https://www.lightningdesignsystem.com/
slds-var-p-horizontal_medium. Few more examples margin,grid,batch,text style,box,brand. 
We can search what CSS/stylesheet code needed, copy pseudo code

<template>
    <lightning-card title="SLDS">
        <div class="slds-var-p-horizontal_medium">
            <div class=" slds-box ">
                <p>This is a regular-sized box.</p>
                <span class="slds-badge">Badge Label</span>
                <span class="slds-badge slds-theme_success">Badge Success</span>
              </div>
        </div
       
    </lightning-card>
    <lightning-card>
        <div class="slds-brand-band slds-brand-band_medium slds-brand-band_group"></div>
    </lightning-card>

</template>

4.  Design Token.
Design tokens are the visual design atoms of the design system — specifically, they are named entities that store visual design attributes. We use them in place of hard-coded values (such as hex values for color or pixel values for spacing) in order to maintain a scalable and consistent visual system for UI development.
Note - Only global action design token can be used in salesforce platform for styling.
Instead of using hard code value we can use token. for example. To have blue text color and white background we can define CSS like 
div{
    color: var(--lwc-brandTextLink);
    background:var(--lwc-brandPrimaryTransparent);
}

5. Shared CSS
When we have common CSS code which are required to be used in multiple components at that time shared CSS is expected to be used. this approach will  code redundancy and easy to maintain.

Assume we have 2 components, component 1 and component 2. both components have common CSS code along with individual CSS code.
 Step - 1 : Create a LWC component named as sharedCSSLWC.
Step -2 : Delete html and JS file from component bundle
Step - 3 : Create CSS file named as sharedCSSLWC.css
Step- 4 : Add common CSS code.
Step - 5 : Go to CSS file of component 1 and import sharedCSSLWC
Step - 6   Go to CSS file of component 2 and import sharedCSSLWC

SharedCSSLWC.css
.mainDiv{
    width:100%;
    background-color: #ddd;
}
.internalDiv{
    text-align:right;
    padding-top:10px;
    padding-bottom: 10px;
    color:white;
}
Component1.css
@import 'c/sharedCSSLWC';
.p{
    width:90%;
    background-color:green;
}
Component2.css
@import 'c/sharedCSSLWC';
.css{
    width:80%;
    background-color:#2196f3;
}

6. Dynamic Styling
Sometime we have assign CSS dynamically. To do so we need to use getter. Assume on user input div width will be controlled. 
There is an input box where percentage will be entered, based on entered value div width will be visible accordingly. 
style={percentage} is the getter.

<template>
    <lightning-card title="Dynamic CSS">

        <div class="slds-var-m-around_medium">
            <lightning-input label="Percentage" type="Number"
                onkeyup={changeHandler} value={percent}>

            </lightning-input>
            <div  style={percentage} class="slds-notify slds-notify_alert slds-theme_alert-texture slds-theme_error" role="alert">
                This is an alert !!!
            </div>
        </div>
    </lightning-card>

</template>
JS file
import { LightningElement } from 'lwc';

export default class DynamicCSS extends LightningElement {
    percent=10;
    changeHandler(event){
        this.percent = event.target.value;
    }

    get percentage(){
        return `width: ${this.percent}%`;
    }
}

7. Styling Across Shadow DOM
This is required when we need to override standard salesforce style. this is not advisable though. We need to follow this when there is no option left. This will have performance impact.

As per shadow dom concept CSS code will not cross boundary even if we apply CSS code externally it will not reach to shadow DOM, it will be applied to parent component. To apply CSS code we need to generate css code from Java script. here is sample code.

Here is component code, It only contains one button. I want to apply CSS to that button. Tried with external CSS by assign class. That class applied only outer element. It could not reach to shadow DOM <button>
<template>
    <lightning-card title="Shadow DOM">

        <div class="slds-var-m-around_medium">
            <lightning-button label="Test" title="Test" class="btnCSS></lightning-button>
        </div>
    </lightning-card>

</template>

To apply CSS to shadow DOM
shadow-d-o-m-l-w-c - component name referenced in kebab case.
Below code will create inline <style> //here css code  </style>tag inside button.
import { LightningElement } from 'lwc';
export default class ShadowDOMLWC extends LightningElement {
    isLoaded = false;
    renderedCallback(){
        if(this.isLoaded) return;
        const style = document.createElement('style');
        style.innerText = `c-shadow-d-o-m-l-w-c .slds-button{
            background: red;    
            color:white;
        }`;
        this.template.querySelector('lightning-button').appendChild(style);
        this.isLoaded = true;
    }
}