This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    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.

    tailwindTailwind
    cssCSS
    Code

    Code

    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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:14 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.

    00:33 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.

    00:56 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.

    01:10 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.

    01:31 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.

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

    Discuss

    Discuss