DEV Community

Cover image for How to use Tailwind CSS
Chris Lojniewski for Pagepro

Posted on • Originally published at pagepro.co

How to use Tailwind CSS

INTRODUCTION

Tailwind CSS has revolutionized the way we, developers build and style web (and mobile) applications. Today I will show you practical aspects of using Tailwind CSS, particularly within React applications, demonstrating how its utility classes can be effectively applied to manage layout, typography, and colour.

In this article, we will explore:

  1. Basic Installation and Configuration of Tailwind CSS: Setting up Tailwind CSS in your project.
  2. Component-Based Styling with Tailwind CSS in React: How to use Tailwind’s utility classes within React components to control layout, typography, and colours.
  3. Advanced Implementation Techniques: How to better align your project’s requirements with advanced features of Tailwind CSS to handle responsive design, custom configurations, and more.

Want to get back to basics? Read What is Tailwind CSS.

HOW TO INSTALL TAILWIND CSS

Step 1: Install Tailwind CSS and Initializa Configuration

First, install Tailwind CSS using npm. Open your terminal and run the following commands in your project directory:

npm install -D tailwindcss

npx tailwindcss init
Enter fullscreen mode Exit fullscreen mode
  • npm install -D tailwindcss installs Tailwind CSS as a development dependency.
  • npx tailwindcss init creates a default tailwind.config.js file in your project. This file is where you will customize Tailwind’s behavior.

Step 2: Set Up Content Paths in Configuration

Tailwind CSS needs to know where your templates are located to scan them for class names. Edit the tailwind.config.js file to include the paths to all of your HTML and JavaScript files. This step helps in removing unused styles and optimising your final CSS bundle.

/ tailwind.config.js

/** @type {import('tailwindcss').Config} */

module.exports = {

  content: ["./src/**/*.{html,js}"],

  theme: {

    extend: {},

  },

  plugins: [],

}
Enter fullscreen mode Exit fullscreen mode
  • content: Specifies the paths to all your HTML and JavaScript files, enabling Tailwind to purge unused CSS.
  • theme: Used to extend Tailwind’s default theme. Customize it according to your design requirements.
  • plugins: Add any official or community-made plugins here to extend Tailwind’s core functionality.

Step 3: Integrate Tailwind Directives into Your Main CSS File

To apply Tailwind’s styles to your project, you need to add Tailwind’s directives to your CSS. These directives act as placeholders that the CLI will replace with actual CSS.

In your project’s CSS file (e.g., src/input.css), add these lines:

/* src/input.css */

@tailwind base;

@tailwind components;

@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode
  • @tailwind base; injects Tailwind’s foundational styles like normalize.css.
  • @tailwind components; includes any custom-designed component classes.
  • @tailwind utilities; applies utility classes, which are the core of Tailwind’s styling mechanism.

Step 4: Compile Your Tailwind CSS

Now, use the Tailwind CLI to transform the directives into concrete styles based on your configuration and the classes used in your templates.

Execute this command to compile your CSS and watch for any changes:

npx tailwindcss -i ./src/input.css -o ./src/output.css --watch
Enter fullscreen mode Exit fullscreen mode
  • -i ./src/input.css points to the input file with your directives.
  • -o ./src/output.css specifies where to save the generated CSS.
  • –watch tells Tailwind to monitor the input files for changes and rebuild the CSS automatically.

Step 5: Reference the Compiled CSS in Your HTML

The final step is to link the generated CSS file in your HTML documents. This enables you to start using Tailwind’s utility classes to style your application.

Link to the compiled CSS in your main HTML file (e.g., index.html):

<!doctype html>

<html>

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="./src/output.css">

</head>

<body>

  <h1 class="text-3xl font-bold underline">

    Hello world!

  </h1>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

You’ve now successfully installed Tailwind CSS and configured your project to use it effectively. With Tailwind’s utility-first approach, you can rapidly design and customize your UI directly within your HTML, facilitating a faster and more responsive development workflow.

HOW TO USE TAILWIND CSS WITH REACT

Using Tailwind with React speeds up the development by allowing you to apply utility classes directly within your React components. Below I’ll show you some examples of how to apply these classes to manage layout, typography, and colour.

Layout

Tailwind’s utility classes make it easy to define your component’s structure. Here’s an example of setting up a simple centered layout in a React component:

<div className="w-full flex justify-center items-center h-screen" />
Enter fullscreen mode Exit fullscreen mode
  • w-full: Sets the width of the element to 100% of its parent container.
  • flex: Applies display: flex; making it a flex container.
  • justify-center: Centers the content along the horizontal axis using justify-content: center;.
  • items-center: Centers the content along the vertical axis using align-items: center;.
  • h-screen: Sets the height of the element to 100vh (viewport height), making it take the full screen height.

Typography

Tailwind provides utilities for typography to control the font weight, size, and more directly within your JSX. Here is how you can style text:

<h1 className="font-bold text-xl">Hello CodeSandbox</h1>
Enter fullscreen mode Exit fullscreen mode
  • font-bold: Applies a font weight of 700, making the text bold.
  • text-xl: Sets the font size to 1.25rem with a line height of 1.75rem.

Colours

Tailwind’s colour utilities allow you to apply colour styles easily. Below is how you can use these classes to add colour to backgrounds and text:

<div className="bg-red-600 text-blue-700">
       <h1 className="font-bold text-xl">Hello CodeSandbox</h1>
       <h2>Start editing to see some magic happen!</h2>
     </div>
Enter fullscreen mode Exit fullscreen mode
  • .text-blue-700: Applies a text color (blue-700 is a specific shade of blue).
.text-blue-700 {
    --tw-text-opacity: 1;
    color: rgb(29 78 216 / var(--tw-text-opacity));
}
Enter fullscreen mode Exit fullscreen mode
  • .bg-red-600: Applies a background colour using Tailwind’s colour scale (red-600 corresponds to a specific shade of red).
.bg-red-600 {
    --tw-bg-opacity: 1;
    background-color: rgb(220 38 38 / var(--tw-bg-opacity));
}
Enter fullscreen mode Exit fullscreen mode

Colours with Arbitrary Values

Tailwind CSS supports using arbitrary values for colours through the bracket notation ([]). This is useful if you need to use a colour that isn’t in the default palette:

<h2 className="text-[#fff]">Start editing to see some magic happen!</h2>
Enter fullscreen mode Exit fullscreen mode
  • .text-[#fff]: Sets the text color to white using Tailwind’s arbitrary value syntax.
.text-\[\#fff\] {
    --tw-text-opacity: 1;
    color: rgb(255 255 255 / var(--tw-text-opacity));
}
Enter fullscreen mode Exit fullscreen mode

Using Tailwind CSS with React improves the development workflow by enabling component-based styling directly within JSX. It eliminates the need for separate CSS files, allowing developers to define styles using utility classes for layout, typography, and colour.

For example, creating a full-screen, centre-aligned layout is straightforward with classes like w-full, flex, justify-centre, items-center, and h-screen. Similarly, setting typography and colour can be done in-line, such as using text-xl and font-bold for font sizing and weight, and bg-red-600 or text-blue-700 for colors. It streamlines the styling process, making it faster and more intuitive.

ADVANCED IMPLEMENTATION

Here’s how to apply advanced Tailwind CSS techniques within React projects, improving component-based styling and overall user experience.

How to Center a Div Using Tailwind in React

To center a div using Tailwind CSS, apply a combination of utility classes that specify full width, flexbox display, center alignment, and full viewport height. Here’s the implementation:

import React from "react";

import ReactDOM from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root")!;

const root = ReactDOM.createRoot(rootElement);

root.render(

  <React.StrictMode>

    <App />

  </React.StrictMode>

);
Enter fullscreen mode Exit fullscreen mode

Practical examples of layout control

For more complex layouts, Tailwind’s grid system and spacing utilities offer fine control:

import React from "react";

import ReactDOM from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root")!;

const root = ReactDOM.createRoot(rootElement);

root.render(

  <React.StrictMode>

    <App />

  </React.StrictMode>

);
Enter fullscreen mode Exit fullscreen mode

Implementing UX Design in Tailwind CSS

Responsive Design and Media Queries

Tailwind’s utility-first approach includes responsive design features that use mobile-first breakpoints:

Mobile-first breakpoints

  • Breakpoint Prefix: Shorthand used in class names to control when a style applies.
  • Minimum Width: The screen width at which these styles become active.
  • CSS: The actual CSS media query used.

For practical application, you can tailor your components to respond to different screen sizes using these breakpoints. For example:

<div className="inner bg-green-100 grid grid-cols-1 md:grid-cols-[20rem_1fr] gap-4">

       …

     </div>
Enter fullscreen mode Exit fullscreen mode
  • grid-cols-1 will be applied on mobile and md:grid-cols-[20rem_1fr] from 768px

If you need to make some changes on a breakpoint that is not preset in a table above you have two options:

  • You can use arbitrary value: min-[328px]:text-blue-200 max-[580px]:text-center
  • You can extend tailwind config:
/** @type {import('tailwindcss').Config} */

module.exports = {

  theme: {

    …

    extend: {

      screens: {

      'custom': '328px',

      // => @media (min-width: 328px) { ... }

    },

    }

  }

}
Enter fullscreen mode Exit fullscreen mode

You can also get rid of the default breakpoints and add only the ones that you need:

/** @type {import('tailwindcss').Config} */

module.exports = {

  theme: {

    screens: {

      small: '400px',

      medium: '850px',

      large: '1024px',

    },

    …

  }

}
Enter fullscreen mode Exit fullscreen mode

Then instead of writing sm:text-center you would use small:text-center

Extending Tailwind with Custom Configurations

Tailwind CSS is highly customizable, allowing you to tailor the framework to meet the specific design needs of your project. This is particularly useful when your design system or style guide includes specific colors, spacing, breakpoints, or typography that differ from Tailwind’s defaults.

Understanding the Tailwind Configuration

The Tailwind configuration file (tailwind.config.js) is where you define your customizations. The theme section of this configuration file allows you to specify how your design tokens such as colors, spacing, and typography should be adjusted or extended.

Overriding vs. Extending:

Overriding the default configuration means replacing the default settings entirely with your custom settings.
Extending the default configuration means adding to or modifying the existing settings without removing the default settings.
Extending the Theme
To extend the existing theme without losing the default configurations, you use the extend key inside the theme object. This approach is preferred when you want to add additional utilities while keeping all the original Tailwind settings.

Example:

/** @type {import('tailwindcss').Config} */

module.exports = {

  theme: {

   extend: {

    colors: {

      transparent: 'transparent',

      black: '#000',

      white: '#fff',

      gray: {

        100: '#f7fafc',

        // ...

        900: '#1a202c',

      },

      // ...

    }

  }

  }

}
Enter fullscreen mode Exit fullscreen mode
  • theme: { extend: { … } }: This structure tells Tailwind that you are adding to the existing theme rather than replacing it.
  • colors:: Inside the extended block, we define our custom colors. This object specifies the colour name as the key (e.g., grey, black) and the corresponding colour value.
  • transparent, black, and white are defined with their respective CSS colour values.
  • gray is an object itself, which allows you to set a spectrum of shades from 100 (light grey) to 900 (dark grey).
  • By placing these inside extend, all other colour utilities provided by Tailwind are preserved, and these new colours are added to the palette.

Overriding the Entire Configuration

This approach involves setting your configurations directly under the theme section without extend, which replaces the entire default configuration with your custom settings.

Example:

/** @type {import('tailwindcss').Config} */

module.exports = {

  theme: {

    colors: {

      transparent: 'transparent',

      black: '#000',

      white: '#fff',

      gray: {

        100: '#f7fafc',

        // ...

        900: '#1a202c',

      },

      // ...

    }

  }

}
Enter fullscreen mode Exit fullscreen mode
  • Direct Definition: Here, the colours are defined directly under the theme.colours property without using extend.
  • Replaces Defaults: This approach replaces all of Tailwind’s default colour utilities with your custom definitions. The default colours will no longer be available unless you redefine them here.

TIPS FOR USING TAILWIND TO ENHANCE USER EXPERIENCE.

  • dark mode – you can use the dark: selector to apply some styles when dark mode is on
  • rems as the base unit – by default, tailwind is using rem as a base unit for all of the spacings, etc. Thanks to this the page will scale properly when different font size is set on the root element
  • pseudo-classes like hover, etc as selectors – if you want to apply a hover effect, or add something on focus, etc., you can use hover:, focus:, etc. selectors. There are also some custom ones, like peer which you can use to style a checkbox, or group which can be used to apply some styles on the element inside a group when the wrapper is hovered, etc.

CONCLUSION

Using Tailwind CSS simplifies the styling process and boosts the overall development workflow by allowing for component-based styling directly within JSX. It eliminates the need for separate CSS files and enables rapid prototyping and customization of user interfaces. By following the steps and techniques outlined in this guide, you c*an effectively use Tailwind CSS to create responsive, accessible, and visually appealing applications that adhere to your design specifications*.

READ MORE

How to build a music streaming app

Next js PageSpeed Improvements

Write Your First E2e Test Using Cypress in 15 Minutes

SOURCES

Tailwind CS installation guide
Tailwind CSS documentation

Top comments (0)