Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Abstract Utility Classes to BEM Components in Tailwind

    Simon VrachliotisSimon Vrachliotis

    When creating UIs with utility classes, a lot of repetition can occur within the HTML markup. In this lesson, we see how this concern can be addressed by extracting a group of tailwind utility classes into a component classname. We create a Blocks Elements and Modifier (BEM) button component with a few style modifiers, that can be used everywhere in our project.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: I have a default tailwind config file which gets processed via Gulp every time the CSS file changes. I also have an index.html file that has a reference to the compile CSS as well as a button composed of tailwind utility classes.

    Say I want a pink button now. I could copy and paste this button element and change the colors to pink. There we go. Let's make one more button but give it a teal background. It's pretty obvious we have a lot of repetition going here. This is not going to scale too well if we have, say, 500 buttons in our application.

    In my style.css file, I'll create a button class. In there, I will use at apply, a custom directive provided by tailwind, and combine utility class together within that class. The hover state classes need to be applied separately. I can now replace all these classes with the button class in my HTML.

    Let's quickly add these two margin classes that I forgot. I use them in this example so my buttons spread out properly, but in general, I recommend leaving margins outside of your component pattern. Let's refresh our page. The button still works.

    Let's replicate this base button a couple of times. We'll create modifier classes for our colors, button--pink and button--teal. In my stylesheet, I will create these classes and apply the right background colors to them. Give that a save. It still works.

    Let's create some more modifiers for the button corners. Button--peel will have the rounded-full class, and button square will have rounded none. Let's create buttons with these classes in our HTML quickly, button peel here and button square here. Give that a save. Whoops, almost there, we must have a typo in our CSS class. Yep, let's fix that.

    Voila! We are now writing bam style components while enforcing the decisions made in the tailwind config file.