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

July 28, 2019 No comments Thymeleaf Conditions CSS class

1. Introduction

Every web developer facing this problem in his/her career at least once in a lifetime. Dynamically adding and removing CSS class is a common functionality and in this article, we will show a way to achieve that in Thymeleaf.

If you need some more information about how to integrate Thymeleaf to your application 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 is used for adding a CSS class to an element without overwriting the existing 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 a 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 append 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 }}