May 10, 2023
Per Djurner

Styling child elements with Tailwind

Every now and then I wish I could style child elements from their parent instead of repeating class names over and over again. Then I remember that this is actually possible with more recent versions of Tailwind!

Here's an example using a description list element.

<dl className="[&>dt]:font-semibold [&>dd]:mb-2">
  <dt>Some term</dt>
  <dd>The description.</dd>
  <dt>Some other term</dt>
  <dd>The description for that other term.</dd>
</dl>

One thing I should note is that the more common approach for handling this is to break out the dt / dd part to a separate component in your favorite framework. That way you can have the class names on the dt / dd elements while still avoiding unnecessary repetition. For simple cases, like the above description list, it feels like overkill to refactor your code to use a separate component though.

Home