Use Dynamic Styling In LWC Salesforce

by Rijwan Mohmmed
0 comment

Hello friends, today we are going to discuss how to Use Dynamic Styling In LWC Salesforce. Our goal here is to learn how to change the class dynamically from js.

Also, check this: Navigate from LWC component to another LWC Component


Key Highlights :

  1. We will add a CSS file to define design classes and ids.
  2. We can assign a CSS class by getter.

Code :

lWCDynamicCSS.HTML :

	<div class="app slds-p-around_x-large">
		<article class={divBackground}>
			<div class="slds-card__header slds-grid">
				<header class="slds-media slds-media_center slds-has-flexi-truncate">
					<div class="slds-media__body">
						<h2 class="slds-card__header-title">
							<a href="#" class="slds-card__header-link slds-truncate" title="Accounts">
					<div class="slds-no-flex">
						<button class="slds-button slds-button_neutral" onclick={handleClick}>Change Background</button>

lWCDynamicCSS.JS :

import { LightningElement } from "lwc";

export default class LWCDynamicCSS extends LightningElement {
  isColorfull = false;

   * Getter for the css property
  get divBackground() {
     return this.isColorfull ? "slds-card backgroundColor" : "slds-card backgroundNoColor";

    this.isColorfull = !this.isColorfull; 

lWCDynamicCSS.CSS :

.backgroundColor {
    background-color: rgb(0, 112, 210);

    background-color: rgb(247, 247, 247)

Output :


Reference :

  1. CSS in LWC

You may also like

Leave a Comment