DEV Community

Cover image for Ultimate guide to building responsive UI elements with Tailwind CSS
Emmanuel Fordjour  Kumah
Emmanuel Fordjour Kumah

Posted on

Ultimate guide to building responsive UI elements with Tailwind CSS

HTML alone does not make a website visually appealing, and will require some CSS to bring life to a website. To achieve that, you can write your own CSS rules to add visuals to HTML element or move faster using CSS frameworks.

CSS frameworks are ready-to-use CSS library that helps frontend developers to quickly create aesthetically appealing user interface which are responsive.

Rather than starting every project from scratch, a CSS framework is made up of numerous CSS stylesheets, which provides a collection of CSS classes that can be applied to any markup to give the element some beauty.

You only have to code the HTML and insert the relevant CSS class to get the design you need.

There are several CSS frameworks available including Bootstrap, Foundation, Bulma and Tailwind.

In this article, we take a look at the Tailwind CSS, and build a responsive QR code component with it. The article will cover the following concepts:

  • Background color
  • Text
  • Font Family
  • Alignment
  • Responsiveness
  • Shadow
  • Padding, margin and borders

Let's get started!

What is Tailwind CSS ?

Tailwind is a utility-first CSS framework that helps developers to quickly build a beautiful and scalable web application.

With Tailwind, you build visual elements like buttons, cards, navbar etc. straight from the markup by inserting the tailwind classes (without touching your CSS file).

Understanding Utility or Atomic CSS

Tailwind's concept is anchored on Atomic CSS, or CSS utility classes. With this concept, a single class applies a single CSS property/value pair to an element.

Take a look at the code below:



.bgr-blue { 
  background-color: #357edd; 
}
.font-weight-bold {
  font-weight: bold;
}


Enter fullscreen mode Exit fullscreen mode

The class bgr-blue and font-weight-bold are declared for a singular purpose.
The function of bgr-blue is only to change the background color of the element it is applied to, to blue.

Likewise, font-weight-bold will only make the font of any element it is applied to bold, it does not add any other styling to the element, meaning, we apply a specific value to an element

We apply the declared classes to our markup like the below:



<p class="bgr-blue font-weight-bold">Some paragraph</p>


Enter fullscreen mode Exit fullscreen mode

This will result in a blue background color with a bold font.

Why Use Utility-first CSS

Using Utility-first or Atomic CSS, your CSS is automatically encapsulated (showing only the most important property-value pair). You style elements by applying pre-existing classes directly in your markup.

Hence, you don't need to worry about accidentally omitting a syntax or breaking something (for instance, you removed a value in your button class that a certain button required), and since the styling rules is in the class, only the HTML elements that have that class names will see the visual effect.

There is no need to write any CSS at all, you only write the markups, and add the class names to the markup. In effect, you are building just about anything with only HTML

So far, we have learned that Tailwind CSS is rooted in a concept called atomic css or utility-first classes, now let's examine some benefits of using Tailwind css

Benefits of Tailwind CSS

Below are some advantages in using Tailwind CSS

  • No need inventing class names: Tailwind saves you a lot of energy in trying to come up with the perfect class name to be used to style something. The work has been done, just used the pre-defined class names, and you are good to go

  • Your CSS stops growing: Using the tradational approach, you will write a lot of CSS to style an element, this will cause the CSS file to grow bigger anytime you want to add new features. However, with Tailwind, you have utilities, so you rarely need to write new CSS

  • Increase performance: Tailwind automatically remove all unused CSS when building for production, making the final CSS bundle the smallest it could be.

  • Responsiveness: Tailwind let you build responsive website right from the markup without battling with a lot of complex media queries.

Due to the advantages outline above, you can quickly build a website using Tailwind.

Prerequisites

Before, we dive into how to set up your project to use tailwind CSS, you should be proficient in the following:

  • HTML
  • CSS

Setting up your project

Open your code editor and navigate to your project directory.

Follow the steps below to setup Tailwind:

Step 1 : Create a package.json file

If you are starting the project from scratch, the package.json file will contain metadata about your project and also keep record of your dependencies.In our case, it will keep record of the Tailwind dependencies we will install later on.

To create the package.json file, follow the steps below:

  • Navigate to your project directory and open your development terminal.
  • Create a package.json file in that directory by running the npm command below.


npm init -y 


Enter fullscreen mode Exit fullscreen mode

Step 2: Install the Tailwind CSS

  1. Install your Tailwind CSS via the npm, type the command below and press the Enter key


npm install -D tailwindcss


Enter fullscreen mode Exit fullscreen mode

Visit the package.json file, and in the list of dev dependencies, you should see tailwindcss if it was successfully installed.

Package file

Next, create the tailwind config file, this file will contain the default configuration for the tailwind classes.

To do that, run the following command in your terminal



npx tailwindcss init


Enter fullscreen mode Exit fullscreen mode

This action will install the tailwind.config.js file in your root directory.

Step 3: Configure the template file

Open the tailwind.config.js, and check the content property.
The content allows us to specify the path to the HTML or JavaScript file where the template for the user interface will be written.

Because, the UI we will be building is not complex, we will keep a simple file structure, so the HTML file we will be using, will be in the root directory of our project

We can then specify the path to this template (i.e the html file) as



content: ["./*.html"],


Enter fullscreen mode Exit fullscreen mode

The action above, will direct Tailwind to look for the HTML file in the root directory. Aftwards, check for any Tailwind classes used in the markup, and compile it to the usually CSS in an output stylesheet

Step 4: Add Tailwind directives to the input file

  • Create the main css file, in my case, I named it input.css (you can give it any prefered name)
  • Next, add the below Tailwind directive to the CSS file


/* input.css */
@tailwind base;
@tailwind components;
@tailwind utilities;


Enter fullscreen mode Exit fullscreen mode

Tailwind will watch this file, compile it and give us all the functionalities we will need to style the UI.

You can also add any custom CSS here (will get to that later)

Step 5: Start the tailwind build process

  • Go to your packages.json file, and in the script property, enter the build script below.
    This script is responsible for processing the functionalities you added to the tailwind CSS file (input.css) into the normal CSS styling.

  • We will also create a second script called watch, which is basically watching the Tailwind CSS file (input.css) for update and convert it to the usual CSS styling.

Add the build and watch script to the script property as below:



 "scripts": {
    "build": "tailwindcss -i ./input.css -o ./css/main.css",
    "watch": "tailwindcss -i ./input.css -o ./css/main.css --watch"
  },


Enter fullscreen mode Exit fullscreen mode
  • Run the script in your terminal with the command npm run build (build is the key given to the script).
  • When successfull, it will output another CSS file called main.css located in a css subdirectory.
  • The i and o in the script represents, input and output respectively.

Image description

During build time, the script will watch and compile the Tailwind CSS file, which in our case is input.css and produce the usual stylesheet named main.css.

Congrats, you have successfully installed the Tailwind CSS, next steps is to write the HTML of the QR code component we will be building

Frontend mentordescription

The Design for the QR code component.

Frontend mentor

frontendddescription

In this tutorial, we will be building a responsive QR Code component from one of Frontend mentor challenges using Tailwind

The Approach

To approach this design, I will first write all the markup for the design.
Later, I will explain the Tailwind concept I will be using, and implement it in our markup.

Remember, the whole idea of Tailwind is to build responsive UI elements without leaving the markup.

How Tailwind works

Taillwind scans all the markup, or JavaScript files for Tailwind class names used on each element.
It will then generate the corresponding styling for the element,and finally write the syntax in a static CSS file.

That said, let's put together the HTML for the design above

The markup of the QR code component.



<body>
    <div>
      <section>
        <img src="./images/image-qr-code.png" />
        <h1>Improve your front-end skills by buidling projects</h1>
        <p>
          Scan the QR code to visit Frontend Mentor and take your coding skills
          to the next level
        </p>
      </section>
    </div>
 </body>


Enter fullscreen mode Exit fullscreen mode

The above is the markup for the design, it is basically a div tag with a section which houses the qrcode image (provided in the images folder of the downloaded assets from Frontend Mentor), the heading is in an h1, and finally the content in a p tag.

Adding the Style sheet

In the head tag of the HTML file, we will link the markup to the CSS file generated in the css subdirectory, which in our case will be the main.css.



<link rel="stylesheet" href="./css/main.css" />


Enter fullscreen mode Exit fullscreen mode

Extending the tailwind Config file

In the frontend Mentor challenge, we were given some style guide for the colors, *font * and font-size to use.

These need to be factored in Tailwind's configuration.
To do that, we will extend the default Tailwind configuration in the tailwind.config.js we created.

In the tailwind.config.js file, there is an extend property, which allows us to add additional functionalities or features to the default Tailwind classes.

For instance, we can indicate our prefered font and colors to use here.

Adding the colors

Let's add our colors defined in the style guide to the Tailwind config file.

  • In the extend property, add another property,colors. The value for the colors is an object
  • The key will be the name of the color to use, and the value can be a hex code,hsl or rgb.
  • For instance, because the background color of our design is light gray, we will have a key, lightGray, with their value as hsl(212, 45%, 89%)
  • Follow the same step for all the other colors to use using the format (colorName : value)

Adding a custom font

Tailwind comes with default font that we can use, we can also add custom font to it.
In this project, we will be using the Outfit font family from Google Fonts.

The below is how to add the font:

  • Go the input css file, in our case, input.css and import the font from Google fonts, this action makes the font available for Tailwind to use
  • @import url("https://fonts.googleapis.com/css2?family=Outfit:wght@600;700&display=swap");

  • Go to the tailwind.config.js file and in the extend property, indicate the font to use

  • Just like we did with the colors, in the extend object, we will define a fontFamiy property and indicate the different fonts we will use in an array

  • Because the entire body of the text is the Outfit font, we will give it a key of body, and then add the array item Outfit, which is the font name.

Tailwind description
So far, we have extended the tailwind.config.js file to add our own colors and font based on the style guide provided.

Tailwind config

Using the Tailwind classes

As mentioned, Tailwind uses low-level utility classes meaning the class used in the HTML have a specific role to play.

Based on the design available,the article will cover the following concepts

  • Background color
  • Text
  • Font Family
  • Alignment
  • Responsiveness
  • Shadow
  • Padding, margin and borders

Adding the Background color

Visit the Tailwind website and in the quick search field, type background color.

This action will display all the utilities for controlling the background color of an element.

Tailwind have a wide range of expertly-crafted default color palette you can rely on.
To control the background color of an element use the class:



bg-{color}


Enter fullscreen mode Exit fullscreen mode

For instance, if I want the background color of my button to be red, in my button element, I will add the class like the below



<button class="bg-red">Click here </button>


Enter fullscreen mode Exit fullscreen mode
  • Write the utility for controlling the background using the bg- prefix followed by the color to use, for instance, red.
  • The class name then becomesbg-red
  • We can also define the shade of red we will need by adding a value to the color.
  • The value ranges from 50 to 900. For instance bg-red-900 will give us the highest red shade as defined in Tailwind

Changing the opacity of the background color

Tailwind gives you the option of controlling the opacity of the background color using the opacity modifier.
The opacity values ranges from 0 to 100, and can be added to change the opacity of the background color.

Using the example above, we can change the opacity like below:



<button class="bg-red-900/50">Click here </button>


Enter fullscreen mode Exit fullscreen mode

Applying background color conditionally

If you want to change the background color when a user hover or focus on an element,Tailwind lets you conditionally apply classes based on different states.

For example, when you add hover:bg-indigo-400 to the button element, it will immediately change the specified background color to indigo when a user hovers the button

Applying the background color to our design

In the above, I introduced you to the background color utilities and how to use the class in your element.

Now, let us use the background color we have defind in the colors property of the tailwind.config.js file.

Based on the design, we need to change the background of the QR code component to light Gray.

To do that, we will add the class bg-lightGray to the body tag.
Remember, lightGray is the name we gave to the preferred color for the backgroud in the tailwind cofiguration.

The snippet is as below:



<body class="bg-lightGray">


Enter fullscreen mode Exit fullscreen mode

We also need to change the main QR component to have a white background,to do that, we add the class bg-white to the section tag as below:



<section class="bg-white">
        <img src="./images/image-qr-code.png" />
        <h1>Improve your front-end skills by buidling projects</h1>
        <p>
          Scan the QR code to visit Frontend Mentor and take your coding skills
          to the next level
        </p>
</section>


Enter fullscreen mode Exit fullscreen mode

Congrats, you have successfully added background colors to the design.

Adding Font

By default, Tailwind provides three font-family utilities: sans-serif stack, a serif stack and monospaced stack.

We can declare the font family of an element using the
font-{name} class.

For instance, if we want the heading below to use the sans font, we will add the class to the h1 element like the below:

<h3 class="font-sans">Change the font</h3>

  • Tailwind will now apply the sans type face on that element.

In the design, we want to use the Outfit font for all the text.
We have already defined that font in the tailwind config file.

To use it, we only need to define it our class.

  • In the body of the HTML, add the font-body class to it

Note, we can use multiple classes on an element by leaving a space between each class name.In the body tag, we have already added the background color and now, we are adding the font.

The below will be the code for adding the Outfit font

<body class="bg-lightGray font-body">

  • We now have to utitlies in the body, one controlling the background color and the other the font

You can also change the font size, font weight, line height, and other typography, be sure to check here for all the font family utilities

Using the Flex utilities

There are utilities for controlling how flex items grow,shrink, and align.This is similar to how we would apply Flex box in the usual CSS.

In our design, we will position the QR code component at the center of the background.

To do that, we give the items a flex property,and use the Align items utilities for controlling how the items are aligned along the cross and main axis.

Find the steps below:

  • Use the flex class to indicate a flex container
  • Position items at the center of the cross axis of the container using the items-center class
  • Position items at the *center of the main axis * of the container using the justify center

In our div tag , we can now apply the flex items-center justify-center utitlities to position the QR code component in the center of the page.

<div class="flex items-center justify-center">

This is similar to



div {
display: flex;
align-items: center;
justify-content: center;
}

Enter fullscreen mode Exit fullscreen mode




Specifying the width of an element

Tailwind provides utilities for setting the width or size of an element.

To do that, use the w- class followed by a value which dictates the size of the element. For instance w-52 will give the element a 208px width.

  • Use the w-{number} or w-px to set an element to a fixed width. For instance, w-20 will give an element a width of 80px
  • Use w-{fraction} or w-full to set an element to a percentage based width. For instance w-full will allow an element to occupy the full width of the container, whilst w-1/2 will occupy half of the width of the container.
  • Use the max-w-{size} class for setting the maximum width of an element
  • Use the min-w-{size} class for setting the minimum width of an element.

Mobile First Design

By default, Tailwind uses a mobile first breakpoint system.What this means is that, unprefixed utilities ( like `max-w-[80%]) will take effect on all screen sizes starting with the smallest screen size.
However, if you want the design to change at a specific breakpoint (or screen size) you will need to add the following breakpoints to the class.

  • sm, md,lg, xl, or 2xl which stands for small, medium, large, extra large, and extra extra large screen sizes respectively.

If we want a design to adapt to particular screen size, we will prefix the utility with the required breakpoint for it to take effect.
For instance, if we want the maximum width of an element to be 50% of the container on a medium size screen and above, we will write it as
<div class="md:max-w-[50%]">...</div>.

Likewise, lg:text-left will align the text to the left only on large size screen and above.

To add a breakpoint use the format
-breakpoint:utility

Targeting mobile devices

Because Tailwind is a mobile-first utility, we use the unprefixed utilities (utilities without any md:,lg: ...) to target mobile, and override them at larger breakpoints using the prefixed utilities.

For instance <div class="text center sm:text-left"></div>

  • This will center text on mobile devices first, and left align the text on small screens (640px) and wider.

It is always a good idea to implement the mobile layout of the design first, and then add the sm, md, lg, xl, 2xl to the utilities to adapt the design at different breakpoints.

Apply the width utility to our design

We want the QR code component to take a maximum width of 80% on mobile.
To do that, add the class max-w-[80%] to section.
On screen size 640px and above, I want the QR code to take up 23% of the screen, hence I will prefix the max-w utility with sm: like the below
sm:max-w-[23%]

`

Adding margin

Tailwind provide utitlites for controlling an element's margin.

Add a margin to one side of element using the m{t|r|b|l}-{size} utilities.
The t|r|b|l stands for the

  • top, right, bottom, and *left * side of the element.

For instance

  • mt-6 would add 1.5rem of margin to the top of element
  • mr-4 would add 1rem of margin to the right of an element
  • mb-8 would add 2rem of margin to the bottom of an element
  • ml-2 would add 0.5rem of margin to the left of an element
Adding horizontal margin

Control the horizontal margin of an element using the mx-size utilities.

For instance, if we want to add margin to the left and right side of a div, we can do so below:

<div class="mx-2"> Adding margins</div>

This will add 0.5rem of margin to the left and right of the element.

Adding vertical margin

Control the top and bottom margin of an element using the my-size utilities.
For instance, if we want to add margin to the top and bottom side of a div, we can do it like the below

<div class="my-5">Vertical margin</div>

  • This will add a margin of 20px to the top and bottom of the element.

In our design, we want to add a top margin of 10rem to the QR code component on mobile devices.

In the section tag, we can add the margin utility class like below
<section class="mt-40...">...</section>

  • On screens with a minimum width of 640px we control the top and bottom sides of the QR code component with sm:my-[10%] and the left and sides sides with sm:mx-[10%]

Adding Padding

There are also utilities for controling an element's padding.

Like margin, we can control the padding on one side of an element using the p{t|r|b|l}-{size} utilities. The t,r,b and l stand for top, right, bottom and left respectively.

For instance, pt-6 would add 1.5rem of padding to the top of an element, pr-4 would add 1rem of padding to the right of an element etc.

  • Add horizontal padding to an element using px-{size} utilities. For instance px-4 would add 1rem of padding to the left and right side of an element
  • Add vertical padding to an element using the py-{size} utilities. For instance py-4 would add 1rem of padding to the top and bottom side of an element.
  • To add padding on all sides of an element using the utility p-{size}. For instance p-8 will add 2rem of padding on all the sides of the element.

Rounding corners

Control the border radius of an element using utilities like rounded, rounded-md, rounded-sm, rounded-lg and rounded-full etc. These classes would control the extent of the radius.

For instance, if we want a circular border radius on a div, we can do it like below:

<div class="rounded-full"></div>

  • If you want to remove an existing border radius from an element, use the round-none utility.

  • To round side separately, use the rounded-{t|r|b|l}{-size} utility. For instance to round only the bottom sides of an element,you can write it as below:
    <div class="rounded-b-lg></div>

  • In our design, we want the white background to have rounded corners on all sides. To do that, use the utility below:

<div class="rounded-2xl"></div>

  • We also want the QR code image to have rounded corners, we implement it as below: <img src="./images/image-qr-code.png" class="rounded-xl" />

Applying Box shaddow color

There are utilities for controlling the color of a box shadow.
Using the shadow without any color value, will apply the default shadow to an element. For instance
<button class="shadow-lg>Click here` will apply the default shadow to the button element.

Use the shadow-{color} utilities to change the color of an existing box shadow, for instance shadow-red will apply a red shaddow on the element.
By default colored shadows will have an opacity of 100%, this can be adjusted using the opacity modifier.

To use a colored shadow, all you need to do is to include the color to use and the opacity value. For instance
<button class="shadow-red-500/40">Click here </button> will apply a red colored shadow to the button.

  • In our design we applied the default shadow to the QR code component using the <section class="...shadow-2xl">...</section>

Summary

In this article, we have learnt how to set up our project to use Tailwind CSS. Tailwind allows us to quickly build the user interace our web app without writing a lot of classes, and without leaving our markup.It offer a mobile-first approach to building user interfaces.

We have covered a lot of Tailwind utilities like Border radius, margin, padding, shaddow,and font, and have used these concept to build the UI of a QR code component.

The code for this tutorial can be found on Github.
Find the final workhere

I will recommend going through the Tailwind docs,and used the knowledge to build projects since that is the only way to learn.

If you have found an insight, issues or have some suggestions to share on this artilce, I would love to hear from you.

Don't forget to also share this article on your various social media platform.
Follow me on Twitter

Top comments (0)