Sling Academy
Home/Tailwind CSS/Using ::before and ::after in Tailwind CSS

Using ::before and ::after in Tailwind CSS

Last updated: December 15, 2023

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.

Next Article: Using :not() selector in Tailwind CSS

Previous Article: Tailwind CSS: How to Create a Vertical Divider Line

Series: Basic Tailwind CSS Tutorials for Beginners

Tailwind CSS

Related Articles