---
title: "Dynamic CSS classes in LWC"
url: "https://blog.beyondthecloud.dev/tips/dynamic-css-classes-in-lwc"
category: "LWC"
tags: "lwc, css, best-practices"
published: "2024-01-02"
---

# Dynamic CSS classes in LWC

Nested ternaries in a class getter stop being readable the moment a second condition appears. A small classSet helper turns the same logic into a flat map of class name to condition.

You've probably encountered code with dynamic CSS classes in LWC done in this way:

```javascript
get wrapperClass() {
    return this.shouldHaveMarginTop ? 'slds-var-m-top_medium' : 'slds-m-top_none';
}
```

Which is not the best solution - once there's gonna be more classes, more conditions - it will become unreadable.

### Use a classSet helper instead

Create a utils or helper component (if you don't have one) and create a classSet function. A basic implementation would look like this:

```javascript
function classSet(config) {
    return Object.keys(config)
        .filter(key => config[key])
        .join(' ');
}

export { classSet };
```

Then import it into your component and start using it:

```javascript
get wrapperClass() {
    return classSet({
        'slds-var-m-top_medium': this.shouldHaveMarginTop,
        'slds-m-top_none': !this.shouldHaveMarginTop
    });
}
```

```markup
<template>
    <div class={wrapperClass}></div>
</template>
```

You can use multiple classes and conditions in that way!
