
How does tailwindcss work?
Oğulcan Bozkurt / 3 Eylül 2024
Tailwind CSS has rapidly become an industry standard, widely adopted by developers for building modern web applications. But what exactly makes it so successful, and how does it work? Let's explore.
What Made Tailwind CSS Successful?
-
Utility-First Approach: Tailwind CSS takes a utility-first approach, which is a significant departure from traditional CSS practices. Normally, you'd create separate CSS files and apply styles by targeting classes, IDs, or tags. This method often leads to scattered styles, making it difficult to maintain and scale your CSS.
-
Avoiding Naming Conflicts: In traditional CSS, you must carefully name classes to avoid conflicts, which can be time-consuming and error-prone. Tailwind simplifies this by using utility classes that describe exactly what they do, like text-sm for small text or border for adding a border. This approach eliminates the need for creative naming conventions and reduces the risk of breaking styles across different components.
-
Reusability and Efficiency: Traditional CSS often results in redundant code as you reuse the same styles across different elements. This can bloat your CSS files, making them harder to manage. Tailwind, however, encourages reusability by allowing you to compose styles directly in your HTML using utility classes. This keeps your styles lean and your codebase more efficient.
<button className="text-sm border"> click me! </button>
In the sample, when you hover over 'text-sm', tailwind intellisense will do what exactly that piece of string does. So 'text-sm' basically means:
.text-sm {
font-size: 0.875rem /* 14px */;
line-height: 1.25rem /* 20px */;
}
How it works?
- Basically in build time, it will scan your files for different class names, then will generate corresponding css for each component.
- Which pages to scan is defines in tailwind config file.
import type { Config } from "tailwindcss";
const config: Config = {
//...
//...
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
// For example in this one, depending on the version of Next.js you're using,
// it will be looking foor your *pages*, *components* and *app* files.
}