DEV Community

Cover image for Build your Flexbox utility CSS classes in 4 simple lines
Safwat Fathi
Safwat Fathi

Posted on

Build your Flexbox utility CSS classes in 4 simple lines

This tutorial assume you have a good understanding of Flexbox. You can read this great article about Flexbox.

Now let's get into business.

What is CSS utility classes?

Utility classes are self-descriptive, single-purpose CSS classes.

.padding-1 {
  padding: 10px;
}
Enter fullscreen mode Exit fullscreen mode

So you can add this utility class to any element, and save time and specific styles to that element.

<div class="padding-1">
    div element with 10px padding
</div>
Enter fullscreen mode Exit fullscreen mode

Of course you have seen this before if you used (TailwindCSS, Bootstrap, Bulma)

But why we bother reinventing the wheel?

There is always use cases when you have to work with HTML and CSS only, no frameworks or even JavaScript allowed.
One of such cases is email templates.

The Problem

Now if we want to implement the concept we discussed earlier to layout our elements with Flexbox we will have to do a long list of CSS classes. Here is why.

.flex {
  display: flex;
}

/* utility classes to align items */
.align-center {
    align-items: center
}

.align-base {
    align-items: baseline;
}

.align-start {
    align-items: flex-start;
}

.align-end {
    align-items: flex-end;
}

/* other utility classes to handle justify property */
/* ... */

/* other utility classes to handle direction */
/* ... */

/* other utility classes to handle gap between elements */
/* ... */
Enter fullscreen mode Exit fullscreen mode

What a MESS right?

Note: before we go on to the soultion check out this article about how to pass values from HTML to CSS.

The Solution

We can make a good use of injecting CSS variables from HTML, here is how.

Our HTML:

<section class="flex" style="--direction: column; --align: center; --justify: center;">
    <div>Element One</div>
    <div>Element Two</div>
</section>
Enter fullscreen mode Exit fullscreen mode

Our CSS:

.flex {
  display: flex;
}

* {
  flex-direction: var(--direction);
  align-items: var(--align);
  justify-content: var(--justify);
}
Enter fullscreen mode Exit fullscreen mode

That is it, by passing down your direction, align and justify values you can have a full control of your layout.

Thank you for reading! I hope this approach could be handy one day to you.

Also don't you think this approach can be very helpful in other use cases? if you do please share your thoughts in the comments, or if you have a better one or enhance my approach please share with us your thoughts in the comments.

Top comments (0)