How to dynamically add/remove CSS classes in Thymeleaf

In this quick article, you'll learn how to dynamically add or remove CSS classes in Thymeleaf using conditionals. 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.

Using th:classappend Attribute

To dynamically add or remove a CSS class to an HTML element, Thymeleaf provides a special appending attribute 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:

<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:

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

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

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

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

<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:

<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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.