Tip #24: Use arbitrary variants in TailwindCSS to style headless CMS content

  • — TailwindCSS

  • 1 min. read

  • — 2/22/2023

Got a bunch of raw HTML coming in from a headless CMS. Want to style all of it with TailwindCSS only? Don't want to use an extra CSS file?

Introducing TailwindCSS's arbitrary variants.

Arbitrary variants are an awesome feature that were recently introduced in TailwindCSS. They let you make arbitrary selectors right in your HTML without the need for custom CSS written in an external CSS file.

Let's learn by example.

Take the following snippet of HTML that was generated via a headless CMS

<div>
    <h1>My blog post</h1>
    <p>This is my blog post, it's currently being used to demo arbitrary variants</p>
    <h2>This is a subsection header</h2>
    <p>I'm some content under the subsection, I'm not as important as the first p tag you saw</p>
    
</div>

To style the h1, h2, and p tags with arbitrary variants, we first need to construct our arbitrary selector.

It will look something like this (for h1): [&>h1]:* where:

  • & represents the currently HTML element (this is the same as & in SASS)
  • >h1 is a CSS selector meaning "select all h1 children in &
  • * is where we put our utilty class

So let's say we want to add mb-4 and text-3xl to our h1 tag.

We can do so like this:

<div class="[&>h1]:mb-4 [&>h1]:text-3xl">
    <h1>My blog post</h1>
    <p>This is my blog post, it's currently being used to demo arbitrary variants</p>
    <h2>This is a subsection header</h2>
    <p>I'm some content under the subsection, I'm not as important as the first p tag you saw</p>
    
</div>

Boom, our h1 is now styled to what we defined using our arbitrary variant.

I recommend using arbitrary variants to do quick, ad-hoc CSS stylings that you would otherwise do in a CSS file like adding stylings for content piped in through a headless CMS.

Happy Tailwinding 💨

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!