Learn Tailwind CSS:  Building & Styling UI Components
Learn Tailwind CSS:  Building & Styling UI Components

By Vinish Bhaskar

Oct 19 2024

Learn Tailwind CSS: Building & Styling UI Components

Welcome to the fifth chapter of our "Learn Tailwind CSS with Examples" tutorial series! In this article, we will focus on styling components. We'll explore how to create common core UI components like buttons, forms, and navigation bars using the utility classes provided by Tailwind CSS.

By the end of this tutorial, you'll clearly understand how to use Tailwind CSS utility classes to style and customize components. You'll be able to easily create attractive and functional UI components without writing complex CSS code. We'll walk through step-by-step examples to help you grasp the concept and apply it to your projects.

So, let's dive into the world of component styling! You'll gain valuable knowledge and skills that will empower you to build visually appealing and user-friendly UI components. Let's get started on this exciting journey! 💪🚀

Tailwind CSS components

In Tailwind CSS, components are like little packages of design that you can use to create different parts of your website. They are like building blocks that you can put together to make a complete user interface.

PS: TailGrids Offers 600+ Pre-built UI Components

Component styling is crucial in Tailwind CSS because it brings many benefits to UI development. Components are like building blocks that make up different parts of a website or app. They have their own styles and can be used again and again.

Each component focuses on a specific function or part of the interface. For example, you might have a component for a navigation bar, a component for a button, or a component for form input. Each component includes all the necessary HTML markup and styling.

One great thing about components is that they are designed to be flexible and reusable. We can use them in different parts of your website or even across multiple projects.

Benefits of Using Components for UI Development:

  • Make the UI look consistent: Components help create a unified and professional look throughout the website or app.
  • Save time and effort: By reusing components, developers can avoid writing the same code multiple times, which speeds up development.
  • Improve organization: Components make it easier to manage and understand the code because each part of the UI is separated into smaller pieces.
  • Support teamwork: With components, different developers can work on different parts of the UI at the same time without causing conflicts.
  • Allow for growth: Components can be modified, combined, or extended as the website or app grows, making it easy to adapt to changes.

To style the components, Tailwind CSS provides utility classes. The utility classes handle all the styling, such as colours, spacing, and typography. This approach allows us to quickly customize and style our components without writing custom CSS code.

Examples of popular component libraries built with Tailwind CSS include Tailgrids" by Pimjo Labs, "Headless UI" by Tailwind Labs, and "Tailwind UI" by the creators of Tailwind CSS. These libraries provide ready-to-use components that can be customized to fit different projects.

Building common UI components

When developing a website or application, it's common to encounter certain UI components that are widely used across different projects. In this section, we'll explore the process of building four standard UI components: buttons, forms, navigation, and cards with images.

1. Button Components:

Buttons are important elements on websites that allow users to perform actions. Tailwind CSS makes it easy to create customizable buttons. Here's a simple guide to creating buttons with Tailwind CSS:

Learn Tailwind CSS:  Building & Styling UI Components

Step 1: Set up the HTML structure:

Start by adding a button element to your HTML code:

<button> Click Me </button>

Step 2: Apply Tailwind CSS classes:

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  Click Me
</button>

To style the button, we use Tailwind CSS utility classes. In the above example, classes like bg-blue-500 set the background colour, hover:bg-blue-700 adds a different colour on hover, text-white sets the text colour, font-bold makes the text bold, py-2 adds padding vertically, px-4 adds padding horizontally, and rounded gives the button rounded corners.

Step 3: Customize the button:

Tailwind CSS offers many utility classes for customization. You can change the button's size by adjusting the padding classes (py-2 and px-4), or modify the colours by selecting different classes from the colour palette.

2. Form Components:

Form elements like input fields, checkboxes, and select menus are crucial for collecting user input. With Tailwind CSS, we can easily style these form components. Here's a guide on building form elements using Tailwind CSS:

Learn Tailwind CSS:  Building & Styling UI Components

We will create a contact form with name and email as input and a submit button.

Step 1: Set up your HTML file: Create an HTML file with the necessary structure for the form. Make sure to include the Tailwind CSS link in the head section. You can use the CDN link or download the Tailwind CSS file and link it locally.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<!-- Add the link to your Tailwind CSS file here -->
  <!--  <link href="path/to/your/tailwind.css" rel="stylesheet"> -->
	<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <title>Contact Form</title>
</head>
<body>
  <div>
    <h2>Contact Form</h2>
    <form action="#" method="POST">
      <div>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
      </div>
      <div>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
      </div>
      <button type="submit">Submit</button>
    </form>
  </div>
</body>
</html>

Step 2: Create the form container:

Inside the <body> tag, create a <div> element to serve as the container for the form. Use the container class to centre the form on the page. Also, add a utility class in the body tag for the background colour.

<body class="bg-gray-500">
  <div class="container mx-auto mt-14 p-6 bg-white rounded shadow-md max-w-md">
    <!-- Form content goes here -->
  </div>
</body>

Step 3: Add utility classes to the form header:

Within the form container, add a utility class to the heading for the form. We'll use the text-2xl class to set the font size to extra-large and font-bold to make it bold.

<body class="bg-gray-100">
  <div class="container mx-auto my-10 p-6 bg-white rounded shadow-md max-w-md">
    <h2 class="text-2xl font-bold mb-4">Contact Form</h2>
    <!-- Form content goes here -->
  </div>
</body>

Step 4: Add utility class to the form :

Now, add the utility class to the form element with two input fields for name and email. We'll use the mb-4 class to add a margin at the bottom of each input field.

<form action="#" method="POST">
      <div class="mb-4">
        <label for="name" class="block text-gray-700 font-bold mb-2">Name</label>
        <input type="text" name="name" id="name" class="w-full py-2 px-3 border border-gray-300 rounded focus:outline-none focus:shadow-outline" required>
      </div>
      <div class="mb-4">
        <label for="email" class="block text-gray-700 font-bold mb-2">Email</label>
        <input type="email" name="email" id="email" class="w-full py-2 px-3 border border-gray-300 rounded focus:outline-none focus:shadow-outline" required>
      </div>
    <!-- submit button goes here -->
 </form>

Step 5: Add the submit button:

Finally, add utility to the submit button to the form. We'll style it with a blue background color using the bg-blue-500 class, and it will change to a darker shade on hover with the hover:bg-blue-700 class. The text color is set to white using text-white, and font-bold makes the text bold. We'll also add py-2 for vertical padding and px-4 for horizontal padding. The rounded class gives the button rounded corners.

<button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">Submit</button>

Step 6. Customize the form components:

You can customize form components using Tailwind CSS utility classes. Adjust the size, colours, spacing, and alignment to match your design.

Here is a live Tailwind CSS playground with the code for the Form Component: https://play.tailwindcss.com/sBuKSCAaaC.

In this playground, you can interact with and modify the code for the Form Component to see how different changes affect its appearance and functionality.

3. Navigation Components:

Tailwind Navbar components and menus help users navigate through a website or app. Tailwind CSS provides techniques for creating responsive navigation components. Here's a simple overview:

Learn Tailwind CSS:  Building & Styling UI Components

Steps to create a navigation component using Tailwind CSS

Step 1: HTML structure for a navigation bar:

<body class="bg-gray-500">
<nav class="w-full px-8 bg-purple-700 text-white py-4">
  <div class="container mx-auto flex items-center justify-between">
    <div class="flex items-center">
      <!-- Navigation content goes here -->
    </div>
  </div>
</nav>
</body>

Step 2: Apply Tailwind CSS classes and add content:

This code creates a navigation bar with a purple background, a profile image, and a name. The navigation menu items are hidden on small screens and revealed as a responsive hamburger menu. Tailwind CSS utility classes are used to style and arrange the elements with simplicity and responsiveness.

Link to live code playground of the Navigation component

<body class="bg-gray-500">
  <nav class="w-full px-8 bg-purple-700 text-white py-4">
        <div class="container mx-auto flex items-center justify-between">
          <div class="flex items-center">
            <img class="rounded-full h-8 w-8 mr-2 md:h-12 md:w-12" src="https://cdn.pixabay.com/photo/2014/04/02/17/07/user-307993_1280.png" alt="Profile Image">
            <h1 class="text-2xl font-bold ">Sophia Johnson</h1>
          </div>
          <ul class="md:flex space-x-8 hidden text-xl font-semibold">
            <li><a href="#" class="cursor-pointer hover:underline">About Me</a></li>
            <li><a href="#" class="cursor-pointer hover:underline">Projects</a></li>
            <li><a href="#" class="cursor-pointer hover:underline">Resume</a></li>
            <li><a href="#" class="cursor-pointer hover:underline">Contact</a></li>
          </ul>
          <div class="md:hidden">
            <a class="text-4xl font-semibold" href="#">&#8801;</a>
          </div>
        </div>
      </nav>
</body>

In the above code snippet, the navigation bar is styled using Tailwind CSS utility classes. Here's a breakdown of the key utility classes used:

  • bg-purple-700: Sets the background color of the navigation bar to a shade of purple (#6B46C1).
  • w-full: Makes the navigation bar span the full width of its parent container.
  • px-8: Adds horizontal padding of 2rem (8px) on both sides of the navigation bar.
  • text-white: Sets the text color inside the navigation bar to white.
  • py-4: Adds vertical padding of 1rem (4px) to the navigation bar.

The navigation content is organized using flexbox:

  • container: Horizontally centers the navigation content using a max-width and automatic left and right margins.
  • flex: Applies a flexbox layout to the content inside the container.
  • items-center: Vertically aligns the navigation content at the center.
  • justify-between: Distributes the navigation content evenly, pushing elements to the edges horizontally.

Within the navigation content:

  • A profile image is displayed with a rounded shape using the rounded-full class. With height and width of 2rem (8px) and 3rem (12px) on medium-sized screens and above (md breakpoint) using h-8, w-8, md:h-12, and md:w-12.
  • Font size of 1.5rem (24px) using text-2xl and bold using font-bold.

For responsive design:

  • The navigation menu items are hidden on small screens using the hidden class and revealed on medium-sized screens and above using md:flex.
  • Menu items are spaced apart horizontally using space-x-8.
  • The "About Me", "Projects", "Resume", and "Contact" links display an underline when hovered over, accomplished using hover:underline.
  • A hamburger menu icon with three lines (&#8801;) is displayed on small screens using md:hidden and is styled with a font size of 4rem (64px) and bold using text-4xl and font-semibold.

By customizing these utility classes, you can easily adjust the appearance and responsiveness of the navigation bar to fit your specific design preferences and requirements.

You can find the live Tailwind CSS playground showcasing the Navigation Component at: https://play.tailwindcss.com/I8bFrvr9cZ.

Feel free to explore the Navigation Component in the playground and experiment with its design and functionality.

4. Card with Image Component:

A card component with an image is a common UI component used to display information or content in a visually appealing way. Creating a card with an image is straightforward using Tailwind CSS. Here's a simple guide:

Step 1: Set Up the HTML Structure Create a new HTML file and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Card Component with Image</title>
  <!-- Add the link to your Tailwind CSS file here -->
  <link href="path/to/your/tailwind.css" rel="stylesheet">
</head>
<body>
  <div>
    <div>
      <img>
      <div>
        <div>Card Title</div>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
      </div>
    </div>
  </div>
</body>
</html>

Step 2: Include Tailwind CSS In the <head> section of your HTML file, add the link to the Tailwind CSS file. You can either use the CDN link or link to a local Tailwind CSS file. Make sure to replace "path/to/your/tailwind.css" with the actual path to your Tailwind CSS file.

Step 3: Create the Card Component

Now, let's create the card component with an image.

<div class="max-w-sm rounded-lg overflow-hidden shadow-md bg-white">
  <img class="w-full" src="path/to/your/image.jpg" alt="Card Image">
  <div class="px-6 py-4">
    <div class="font-bold text-xl mb-2">Project Name</div>
    <p class="text-gray-700 text-base">Project Descriptipn: Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  </div>
</div>

Step 4: Customize the Card

The card is represented by an <div> element with classes max-w-sm, rounded-lg, overflow-hidden, shadow-md, and bg-white. These classes give the card a rounded shape, hide overflowing content, add a shadow effect, and set a white background.

Step 5: Add an Image

<div class="container mx-auto mt-8">
    <div class="max-w-sm rounded-lg overflow-hidden shadow-lg bg-slate-100">
      <img class="w-full" src="path/to/your/image.jpg" alt="Card Image">
      <div class="px-6 py-4">
        <div class="font-bold text-2xl mb-2">Card Title</div>
        <p class="text-gray-900 text-l">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
      </div>
    </div>
  </div>

Inside the card, you'll find an <img> element with the class w-full. The w-full class ensures that the image takes up the full width of the card container. Replace "path/to/your/image.jpg" with the actual path to your image file.

Step 6: Card Content

The card content, such as the title and description, is placed within a <div> with classes px-6 and py-4. The px-6 class adds horizontal padding, and py-4 adds vertical padding.

Step 7: Customize Card Content

Within the card content <div>, you'll find a title and a paragraph. The title is represented by a <div> element with classes font-bold and text-xl, making it bold and setting the font size to extra-large.

The paragraph is represented by a <p> element with classes text-gray-700 and text-base. The text-gray-700 class sets the text color to a shade of gray (#4A5568), and text-l sets the font size.

Step 8: Preview and Customize

Open the HTML file in your browser to preview the card component with the image. You can further customize the card's appearance by applying more Tailwind CSS utility classes, changing colors, adjusting padding, and adding more content as needed.

Here is a live Tailwind CSS playground featuring the Card Component with an image: https://play.tailwindcss.com/l7LSUVx3PL.

In this playground, you can explore the Card Component with an image and experiment with its layout and styling to see how it looks with different changes.

Learn Tailwind CSS:  Building & Styling UI Components

With these steps, you've successfully created a basic card component with an image using Tailwind CSS. Utility classes make it simple to style and customize components, allowing us to create visually appealing and responsive designs without writing custom CSS."

We will use these components for building our portfolio in this tutorial series. These components will help us create a professional and visually appealing portfolio that showcases our skills and projects effectively.

Styling components with utility classes and customizations

Utility classes in Tailwind CSS are simple and specific CSS classes that provide specific styling properties. They're easy to use and can be combined to create different looks for your components. Each utility class focuses on a specific aspect of styling, such as colors, typography, spacing, or positioning.

For example, let's say you want to change the color of a text element to red. In Tailwind CSS, you can apply the text-red-500 class to the element, where the text indicates the utility class for text styling, red specifies the color, and 500 represents the shade or intensity of the color. This makes it easy to quickly apply styles without the need to write custom CSS.

Applying Utility Classes to Style Components:

To style components using utility classes, you can directly apply the relevant classes to the HTML elements that make up the component.

Let's consider the above button component as an example:

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  Click Me
</button>

In the above code snippet, the button element has several utility classes applied to it. The bg-blue-500 class sets the background color to blue, hover:bg-blue-700 changes the background color when the button is hovered over, text-white sets the text color to white, font-bold makes the text bold, py-2 adds vertical padding, px-4 adds horizontal padding, and rounded gives the button rounded corners.

Similarly in Card with Image Component :

<div class="max-w-sm rounded overflow-hidden shadow-lg">
  <img class="w-full" src="image.jpg" alt="Card Image">
  <div class="px-6 py-4">
    <!-- Card content goes here -->
  </div>
</div>

In the above code snippet, the card with an image component is styled using Tailwind CSS utility classes. The max-w-sm class sets the maximum width of the card, rounded gives it rounded corners, overflow-hidden hides any content that exceeds the card's boundaries, shadow-lg adds a shadow effect, w-full makes the image fill the card's width, px-6 adds horizontal padding to the card's content, and py-4 adds vertical padding to the card's content.

By combining and customizing utility classes, we can easily style various components in Tailwind CSS.

Utilizing Utility Class Variations for Different Component States:

It provides utility classes that enable us to style components differently based on different states, such as hover, focus, or active. These classes are prefixed with state-specific keywords.

For instance, to change the background color of a button when it is hovered over by the user, you can use the hover:bg-blue-700 class. This will modify the background color to a darker shade of blue when the button is hovered over. Similarly, we can use focus:outline-none to remove the outline around a button when it is focused, resulting in a cleaner appearance.

By utilizing these utility class variations, you can easily enhance the interactivity and visual feedback of your components based on user interactions.

We can even use our custom utility classes for customization. We have already covered this topic in the previous chapter on 'Customization' in A Comprehensive Guide to Customization and Extension.

Conclusion

And with that, we finish the fifth chapter of our tutorial series, "Learn Tailwind CSS with Examples." In this chapter, we focused on building and styling components using Tailwind CSS. We explored how to create common UI elements like buttons, forms, navigation bars, and cards with images using the utility classes provided by Tailwind CSS.

We started this chapter by understanding the importance of components in web development. Components are like small design packages that act as building blocks for creating a unified user interface. They make it easier to manage and reuse design elements, saving time and effort during development.

Then we built some common UI components i.e. buttons, forms, navigation bars, and cards with images. With utility classes, we have created attractive and responsive designs without needing complex custom CSS code.

We also explored utility class variations for different component states like hover and focus. These variations let us add interactivity and visual feedback to our components, making them more engaging for users.

At the end of this chapter, we learned about the component's styling and the benefits of using custom utility classes for extra customization and branding.

With the knowledge gained, you can confidently create consistent and professional-looking components. Tailwind CSS's flexibility and reusability, along with its powerful utility classes, make it an excellent tool for UI development.

Remember to keep practicing and experimenting with Tailwind CSS. The more you work with it, the better you'll become. We hope you enjoyed this tutorial series, and we wish you success in your web development journey.

Happy coding! 🚀

Share This Post

Related Articles

Learn Tailwind CSS: Best Practices and Performance Optimization
Tutorial Series

Learn Tailwind CSS: Best Practices and Performance Optimization

Welcome to Chapter 9 of our "Learn Tailwind CSS" tutorial series! In this chapter, we'll learn more about improving perf...

Learn Tailwind CSS: Integrating Tailwind CSS with Frameworks and Tools
Tutorial Series

Learn Tailwind CSS: Integrating Tailwind CSS with Frameworks and Tools

Welcome to chapter eight of our " Learn Tailwind CSS " tutorial series! In this chapter, we'll take your Tailwind CSS sk...

Learn Tailwind CSS: Basic Usage and Utility Classes
Tutorial Series

Learn Tailwind CSS: Basic Usage and Utility Classes

Welcome to the second chapter of our “ Learn Tailwind CSS with Examples” tutorial series! In this article, we will expl...