How to dynamically add/remove a CSS class in Thymeleaf?

September 22, 2019 No comments Thymeleaf Conditions CSS class

1. Introduction

In this article, we will show methods to dynamically add and remove CSS class in Thymeleaf templates. This functionality is commonly used by developers, everyone face that problem at least once in his/her career.

If you need some more information about how to integrate Thymeleaf with Spring Boot application, or how to use conditions, please check below links:
Spring Boot with Thymeleaf
Using conditions in Thymeleaf
How to use if-else in Thymeleaf with Spring Boot?

2. Using th:classappend attribute

Thymeleaf comes with th:classappend attribute that was created for adding a style class to an element without overwriting the existing defined classes.

The following example shows how to use it conditionally:

<div class="panel" th:classappend="${condition} ? 'white' : 'black'"></div>

If ${condition} is true the rendered website will look like the following:

<div class="panel white"></div>

when ${condition} is false the result will be:

<div class="panel black"></div>

Thymeleaf gives the ability to provide an inline condition without else command, that will looks like the following:

<a href="/something" th:classappend="${condition}? 'tag'" class="link">Link</a>

In this case when ${condition} is false, null will be returned and no class will be appended to the attribute.

3. Conclusion

This article showcased the easy way to conditionally add/remove a class to any element in Thymeleaf. Special attribute th:classappend seems to be the best solution, because it appends class not replace existing ones.

{{ message }}

{{ 'Comments are closed.' | trans }}