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.

Last Updated: