# How to dynamically add/remove CSS classes in Thymeleaf

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jan 29, 2020. Topics: Thymeleaf.
Canonical URL: https://attacomsian.com/blog/thymeleaf-dynamically-add-remove-css-classes

> A quick guide to learn how to dynamically add or remove a CSS class in Thymeleaf.

In this quick article, you'll learn how to **dynamically add or remove CSS classes** in Thymeleaf using [conditionals](https://attacomsian.com/blog/thymeleaf-conditions). Thymeleaf is a popular server-side template engine for Java-web web and standalone applications. To learn more about how to use Thymeleaf with Spring Boot, check out [this guide](https://attacomsian.com/blog/spring-boot-thymeleaf-example).

## Using `th:classappend` Attribute

To dynamically add or remove a CSS class to an HTML element, Thymeleaf provides a special [appending attribute](https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appending-and-prepending) called `th:classappend` which can be used for adding a CSS class without overwriting already defined classes.

The following example demonstrates how to use `th:classappend` to conditionally add a CSS class:

```markup
<button class="btn" th:classappend="${condition} ? 'primary' : 'warning'">
    Click Here!
</button>
```

Now if the `${condition}` evaluates to **true**, Thymeleaf template engine will render the following HTML:

```markup
<button class="btn primary">Click Here!</button>
```

Otherwise, the rendered HTML will look the below if `${condition}` evaluates to **false**:

```markup
<button class="btn warning">Click Here!</button>
```

You can even **add multiple CSS classes** using the `th:classappend` attribute as shown below:

```markup
<div class="row" th:classappend="${condition} ? 'container mt-3' : 'container-fluid'">
    <h1>Welcome to Thymeeleaf!</h1>
</div>
```

Thymeleaf also allows to **specify an inline condition without the else part** as shown below:

```markup
<a th:href="@{https://google.com}" th:classappend="${condition} ? 'external-link'">
    Google it!
</a>
```

In the above case, if `${condition}` is **false**, no CSS class will be appended to the anchor tag.

## Conclusion

This quick article, we looked at Thymeleaf's `th:classappend` attribute to conditionally add or remove CSS classes from an HTML element. This attribute is very useful to dynamically append CSS classes to an element without overwriting the existing classes.

Thymeleaf provides plenty of useful attributes that make it ideal for modern HTML5 Java-based web development. If you want to learn more about how to start working with Thymeleaf in Spring Boot, check out the [this tutorial](https://attacomsian.com/blog/spring-boot-thymeleaf-example).
