iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌪️

Practical Guide to Tailwind CSS for Professional Development

に公開

Introduction

I'm Yuma, an intern at var, Inc. During my training before joining the actual project, I received code reviews from active frontend engineers and learned the basics of how to use Tailwind. I hope that by sharing the knowledge I gained during my training, I can help others who are also in the process of learning.

Target Audience

  • Those interested in Tailwind who want to learn the basic usage
  • Those who want to use Tailwind effectively in team development, such as hackathons
  • Those who have been using Tailwind somewhat aimlessly (like myself before the training)

Goals of this Article

  • Understand basic configuration and customization methods for Tailwind
  • Understand efficient class name management methods
  • Understand practical styling techniques using Tailwind

Prerequisites

Customizing Tailwind with tailwind.config.js

You can set project-specific styling in tailwind.config.js. In this configuration file, you can predefine basic design elements such as colors and font sizes. By leveraging these settings, developers can easily implement consistent designs and respond flexibly to future changes and extensions.

In professional practice, it is common for designers to specify colors and fonts using tools like Figma. Therefore, use tailwind.config.js to efficiently apply styles according to design specifications.

Below is an example of basic color, font family, and font size settings in tailwind.config.js.

// tailwind.config.js
import type { Config } from "tailwindcss";
import defaultTheme from "tailwindcss/defaultTheme";

const config: Config = {
  content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
  theme: {
    // Color settings
    colors: {
      // Basic colors
      blue: "#1fb6ff",
      purple: "#7e5bef",
      pink: "#ff49db",
      orange: "#ff7849",
      green: "#13ce66",
      yellow: "#ffc82c",
      black: "#000000",
      // Detailed grayscale settings
      gray: {
        900: "#333333",
        800: "#666666",
        700: "#999999",
        600: "#CCCCCC",
        100: "#EEEEEE",
      },
      white: "#FFFFFF",
    },
    // Font family settings
    fontFamily: {
      sans: ["Graphik", "sans-serif"],
      serif: ["Merriweather", "serif"],
    },
    // Font size settings
    fontSize: {
      xs: ["0.75rem", { lineHeight: "1rem", letterSpacing: "0.03em" }],
      sm: ["0.875rem", { lineHeight: "1.25rem", letterSpacing: "0.03em" }],
      base: ["1rem", { lineHeight: "1.5rem", letterSpacing: "0.03em" }],
      lg: ["1.125rem", { lineHeight: "1.75rem", letterSpacing: "0.03em" }],
      xl: ["1.25rem", { lineHeight: "1.75rem", letterSpacing: "0.03em" }],
      "2xl": ["1.5rem", { lineHeight: "2rem", letterSpacing: "0.03em" }],
      "3xl": ["1.875rem", { lineHeight: "2.25rem", letterSpacing: "0.03em" }],
      "4xl": ["2.25rem", { lineHeight: "2.5rem", letterSpacing: "0.03em" }],
      "5xl": ["3rem", { lineHeight: "1", letterSpacing: "0.03em" }],
    },
  },
  plugins: [],
};

You can use this configuration to apply classes as follows:

// Example of component usage
<div className="bg-blue font-sans text-lg">Sample text</div>

By utilizing tailwind.config.js in this way, you can maintain design consistency while increasing development efficiency.

I recommend implementing font and color settings by referring to the Tailwind official documentation.

*Note: Setting this up will disable the default Tailwind color palette, such as bg-blue-500.

Defining Common Page CSS in globals.css

Although it is not directly related to Tailwind, you can set basic styles shared across the entire project in globals.css. By using Tailwind's @layer directive, you can incorporate these styles into Tailwind's base layer. This allows you to override or add custom styles to Tailwind's default base styles.

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  body {
    font-size: theme(fontSize.base);
    font-weight: theme(fontWeight.medium);
    font-family: theme(fontFamily.sans);
    color: theme(colors.gray.100);
    background-color: theme(colors.black);
  }
}

The code above uses the theme function to reference the theme settings in tailwind.config.js.

For more on how to use CSS and @layer, please refer to here.

Leveraging the cn() function for efficient class name management

Here, I will explain the introduction and benefits of a custom helper function cn() that combines clsx and tailwind-merge. This cn() function is defined in src/libs/utils.ts and can be used throughout the project.

npm install tailwind-merge clsx
import clsx, { ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

This function easily combines multiple class names and efficiently resolves conflicts among Tailwind CSS utility classes. Now, let's look at the difference between using and not using cn().

Without the cn() function

// Button.tsx
const Button = ({ size, children }) => {
  let sizeClass = "";
  if (size === "sm") {
    sizeClass = "text-sm px-3 py-1";
  } else if (size === "md") {
    sizeClass = "text-base px-4 py-2";
  } else if (size === "lg") {
    sizeClass = "text-lg px-5 py-3";
  }

  return <button className={`border rounded ${sizeClass}`}>{children}</button>;
};

In this code, sizeClass is set manually based on the size prop. While this is intuitive, the code becomes long and complex as size options increase.

With the cn() function

// Button.tsx
import { cn } from 'src/libs/utils';

const Button = ({ size, children }) => {
  return (
    <button
      className={cn(
        'border rounded',
        {
          'text-sm px-3 py-1': size === 'sm',
          'text-base px-4 py-2': size === 'md',
          'text-lg px-5 py-3': size === 'lg',
        }
      )}
    >
      {children}
    </button>
  );
};

Using the cn() function makes combining class names very concise. By placing common CSS in the first argument and specifying conditional class names in object format as the second argument, the cn() function selects and combines the appropriate classes. This improves code readability and scalability.

References

https://tailwindcss.com/docs/configuration
https://youtu.be/cZc4Jn5nK3k?si=EvvfOIZgY8fCh7BY
https://ui.shadcn.com/docs/installation/manual#add-a-cn-helper
https://www.youtube.com/watch?v=re2JFITR7TI

Conclusion

Our company operates an infrastructure learning site, Envader, and an IT school (RareTECH). We also conduct corporate training and system development, so please contact us through our website if you are interested.

https://envader.plus
https://raretech.site
https://var.co.jp

We are also looking for new colleagues to join us.

  • Frontend Engineer
  • Bubble Engineer
  • Mentor for IT school RareTECH
  • Web Marketer

We are strengthening our recruitment activities for various positions. If you are interested, please contact us via the Wantedly link below.

https://www.wantedly.com/companies/var/projects

Discussion