Using ::before and ::after in Tailwind CSS

Updated: December 15, 2023 By: Khue Post a comment

In Tailwind CSS, you can add the ::before and ::after pseudo-selectors by using the before and after modifiers, respectively. You can use these modifiers to insert content (and style this inserted content as well) before and after an element without changing the HTML code.

You can combine the before and after modifiers with other modifiers like hover, disabled, checked, etc, as needed (see the second example).

Example 1

Screenshot:

The code:

<body>
    <div class="p-20">
        <div class="w-96 h-24 bg-rose-700 p-20
            before:content-['Hello'] before:text-sky-300 before:text-4xl
            after:content-['Goodbye'] after:text-amber-300 after:text-4xl
            ">
            <h1 class="text-4xl text-white">SlingAcademy.com</h1>
        </div>
    </div>
</body>

Example 2

In this example, before content, and after content are only added when the mouse hovers over the box:

The code:

<body>
    <div class="p-20">
        <div class="w-96 h-72 bg-indigo-700 p-20
            hover:before:content-['Hello'] before:text-sky-300 before:text-4xl
            hover:after:content-['Goodbye'] after:text-amber-300 after:text-4xl
            ">
            <h1 class="text-4xl text-white">SlingAcademy.com</h1>
        </div>
    </div>
</body>

See also: Tailwind CSS: How to Create a Stepper.