DEV Community

Cover image for How to use ::before and ::after in Tailwind CSS
Jatin Sharma
Jatin Sharma

Posted on • Updated on

How to use ::before and ::after in Tailwind CSS

In this article we are going to learn that how you can use ::before and ::after selectors in Tailwind CSS. If you don't know what Tailwind CSS is then you should look into it because it's just awesome. And trust me If you got used to it then you could not leave.

Now let's continue with this article. This feature is only available in Just-in-Time (JIT) mode. Tailwind has first-party support for styling pseudo-elements like before and after:

<div class="before:absolute before:bg-blue-500 after:flex after:bg-blue-300" ></div>

Enter fullscreen mode Exit fullscreen mode

It has content: "" by default so you don't need to worry about that. Any time you use a before or after variant to make sure the elements are rendered, but you can override it using the content utilities which have full arbitrary value support:

<div class="before:content-['hello'] before:block ..."></div>
Enter fullscreen mode Exit fullscreen mode

You can even grab the content from an attribute using the CSS attr() function:

<div
  before="hello world"
  class="before:content-[attr(before)] before:block ..."
></div>
Enter fullscreen mode Exit fullscreen mode

This can be super helpful when your content has spaces in it since spaces can't be used in CSS class names. You can use mostly any property with before and after

Conclusion

Tailwind is the super awesome framework of CSS. According to me, it's the best so far. Everyone should learn it and it is very easy to learn and use. For more such articles consider a Follow.

Also Read

Top comments (9)

Collapse
 
mrexito profile image
Raul

Unfortunately, your article didn't help me. I still don't understand the usefulness of these selectors. I copied your code to see what it does but doesn't work. Why not given a working code?
Thank you

Collapse
 
j471n profile image
Jatin Sharma

Here's the working code:

play.tailwindcss.com/hzprtkooCV

Collapse
 
komorebicqd profile image
chenqiaoda

<div
class="relative mx-auto mt-20 h-96 w-96 rounded-lg bg-black shadow-md before:content-[''] before:absolute before:h-10 before:rounded-full before:w-10 before:bg-blue-300"
/>

Collapse
 
barisdogansutcu profile image
Barış Doğan Sütçü

thx a lot.

Collapse
 
j471n profile image
Jatin Sharma

I am glad, it helped you. :)

Collapse
 
kwadoskii profile image
Austin Ofor

i was omitting this before:absolute and my before was not showing.

Thanks

Collapse
 
bekiryazgann profile image
Ebubekir Yazgan

You may have forgotten to give relative to the parent element.

Collapse
 
eduardoalmeidabr profile image
eduardoalmeidabr

What if I want to use unicode like:

  • ...
  • ?

    \f107: Font Awesome arrow down

    Collapse
     
    emrebiberoglu profile image
    Emre Biberoğlu

    You can use before:content-['\f107']