Thymeleaf - Dynamically Add or Remove a CSS Class - th:classappend Attribute

In this article, we will discuss how to dynamically add and remove CSS class in Thymeleaf templates. 

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' : 'red'"></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 red"></div>
Thymeleaf gives the ability to provide an inline condition without else command, that will look 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.

Comments

  1. Hello, an amazing Information dude. Thanks for sharing this nice information with us. Broward Family Law Mediator

    ReplyDelete

Post a comment