Skip to content

Tailwind CSS - Content

Tailwind CSS: Working with Pseudo-Element Content

Section titled “Tailwind CSS: Working with Pseudo-Element Content”

Tailwind provides utilities to control the content property, most commonly used with the ::before and ::after pseudo-elements. This allows you to add decorative or supplementary content to elements directly from your HTML.

The primary utilities for content involve using variants like before: and after: combined with the content utility.

Class ExampleCSS Output
after:content-[’*‘].after:content-['']::after { content: ''; }
before:content-[attr(data-tooltip)].before:content-[attr(data-tooltip)]::before { content: attr(data-tooltip); }
content-none.content-none { content: none; }

These utilities are powerful for small UI decorations. Modern Tailwind uses arbitrary values (the [...] syntax) to allow for any string content.

A common use case is adding a red asterisk * to the label of a required form field.

<div class="space-y-4 p-4">
<label for="name" class="block text-sm font-medium text-gray-700">
Name
</label>
<input type="text" id="name" class="border border-gray-300 rounded-md p-2 w-full">
<label for="email" class="block text-sm font-medium text-gray-700
after:content-['*'] after:ml-0.5 after:text-red-500">
Email (Required)
</label>
<input type="email" id="email" class="border border-gray-300 rounded-md p-2 w-full">
</div>

You can replace default list bullets with custom content, like an emoji or an SVG icon.

<ul class="list-none space-y-2 p-4">
<li class="before:content-['✅'] before:mr-2">
Modern project setup
</li>
<li class="before:content-['✅'] before:mr-2">
Clean, readable code
</li>
<li class="before:content-['❌'] before:mr-2 text-gray-400">
Outdated practices
</li>
</ul>

Example 3: Using Data Attributes for Content

Section titled “Example 3: Using Data Attributes for Content”

For more dynamic content, you can pull text from an HTML data attribute. This is useful for simple tooltips or quotes.

<blockquote
class="p-4 bg-gray-100 border-l-4 border-gray-400 italic
before:content-[open-quote] after:content-[close-quote]"
cite="Ada Lovelace"
>
<p class="mb-2">The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform.</p>
<footer class="text-right text-sm text-gray-600 after:content-['—_attr(cite)']"></footer>
</blockquote>

Warning: Content added via ::before and ::after is often not announced by screen readers. It should be treated as purely decorative.

  • Do not use pseudo-elements to add critical information, such as error messages or important labels.
  • Do use them for stylistic elements like custom bullet points, quote marks, or decorative icons that have a text-based alternative nearby.