Sub topic 1
The Utility-First Approach
Prerequisites
You should know React components, props, and JSX. You should understand basic CSS, including the box model, flexbox, and media queries. You should also be comfortable with npm, Vite, and basic TypeScript or JavaScript.
The utility-first approach
Tailwind CSS is a utility-first CSS framework. A utility class applies one small CSS rule, such as p-6 for padding or text-gray-900 for text color. You compose these classes directly in JSX instead of creating a separate CSS selector for each component.
This differs from custom CSS and CSS Modules. Those approaches usually give a component a class name, then define many rules in a stylesheet. Tailwind keeps the styling close to the markup and generates CSS only for classes it detects in your source files.
Setting up Tailwind in a Vite and React project
In a Vite project, install Tailwind and its Vite plugin:
npm install tailwindcss @tailwindcss/viteRegister the plugin beside the React plugin:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
})In the stylesheet imported by your React entry file, load Tailwind:
@import "tailwindcss";Styling with core utilities
Core utilities cover common design properties. For example, rounded-lg sets the corner radius, p-6 sets padding, and shadow-sm adds a small shadow:
export function ProfileCard({ name, role }: { name: string; role: string }) {
return (
<div className="max-w-sm rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
<h2 className="text-lg font-semibold text-gray-900">{name}</h2>
<p className="mt-1 text-sm text-gray-600">{role}</p>
</div>
)
}Building layouts with flexbox and grid
Tailwind maps directly to CSS layout concepts. Use flex, items-center, and justify-between for flexbox. Use grid, column utilities, and gap-* for grid layouts.
export function CardGrid({ children }: { children: React.ReactNode }) {
return (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{children}
</div>
)
}The grid has one column by default, two at the sm breakpoint, and three at lg.
Exercise
What does the gap-4 utility do in the CardGrid component?
Show answer
It adds consistent spacing between the grid items.