1. Overview

In this quick tutorial, we’ll learn a few different ways to conditionally add CSS classes in Thymeleaf.

If you are unfamiliar with Thymeleaf, we recommend checking our introduction to it.

2. Using th:if

Let’s assume that our goal is to generate a _ whose classes are determined by the server:

<span class="base condition-true">
   I have two classes: "base" and either "condition-true" or "condition-false" depending on a server-side condition.
</span>

Before this HTML is served, we need a good way for the server to evaluate a condition and either include the condition-true class or the condition-false class, as well as a base class.

When templating HTML, it’s quite common to need to add some conditional logic for dynamic behavior.

First, let’s use th:if to demonstrate the simplest form of conditional logic:

<span th:if="${condition}" class="base condition-true">
   This HTML is duplicated. We probably want a better solution.
</span>
<span th:if="${!condition}" class="base condition-false">
   This HTML is duplicated. We probably want a better solution.
</span>

We can see here that this will logically result in the correct CSS class being attached to our HTML element, but this solution violates the DRY principle because it requires duplicating the entire block of code.

Using th:if can certainly be useful in some cases, but we should look for another way to dynamically append a CSS class.

#css #developer

Conditional CSS Classes in Thymeleaf
3.70 GEEK