We encounter a no of scenarios in which we require dynamic styling in LWC component development. In this blog, we will learn about changing and setting class dynamically from js.

We all know that in order to write any custom style we can add a css file in our LWC component named with the app name. Ex: If my component name is paginator then I can create a paginator.css file parallel to paginator.html and paginator.js.

There can be a various use case, here we will discuss two.

Usecase 1:

In your app, you want to provide a setting for admin to decide theme styling like background color button colors, etc. Basis of its selection UI has that change

To achieve this you can declare a property in your js file and the basis of your setting can change the value of the property. That property can be used as a class. Ex :


SampleApp html


Sample App CSS


sampleApp js Salesforce
Also Read: How To Use Properties In Lightning Web Component?

Usecase 2:

In your app, you want to add or remove styling from any element

Let’s say I have a div and I want to add or remove a class from my div element.


Sample App HTML 1


SampleApp CSS 1

sampleApp.jssampleApp js dynamic components

In this example, I have used basic js to manipulate styling in my div element.

Hope this example helps you to solve all your dynamic styling related needs. If you need further assistance regarding a project of yours then get in touch with our salesforce consulting team. Our team consists of expert developers providing salesforce development services for various salesforce products.

Learn More: How To Call Apex Method In Lightning Web Components?

Avatar photo

With a decade of experience in eCommerce technologies and CRM solutions, Virendra has been assisting businesses across the globe to harness the capabilities of information technology by developing, maintaining, and improving clients’ IT infrastructure and applications. A leader in his own rights his teammates see him as an avid researcher and a tech evangelist. To know how the team Virendra can assist your business to adopt modern technologies to simplify business processes and enhance productivity. Let’s Talk.