tezvyn:

Stylelint: Your CSS Guardian for Rules, Not Just Formatting

AI-drafted, machine-checkedSource: stylelint.iointermediate

Stylelint is a linter that guards your CSS logic and conventions, not just its formatting. Use it to catch errors like misspelled properties or enforce team rules. The footgun is confusing it with a formatter; Stylelint enforces rules, Prettier handles style.

WHY IT EXISTS CSS is notoriously forgiving, which allows browsers to render pages even with errors. This flexibility can hide mistakes and lead to inconsistent, hard-to-maintain codebases, especially on large teams. Stylelint was created to programmatically enforce quality and conventions, preventing errors and maintaining a unified style guide across all CSS, SCSS, or CSS-in-JS files.

THE MENTAL MODEL Think of Stylelint as a strict but helpful code reviewer for your stylesheets. While a formatter like Prettier makes your code look neat, Stylelint ensures your code is correct and follows the project's rules. It cares about the logic and structure, not just the whitespace. It asks, "Is this a valid, high-quality, and conventional way to write this style?"

HOW IT WORKS Stylelint parses your CSS into an abstract syntax tree (AST). It then runs a configured set of rules against this tree. Each rule checks for a specific pattern or anti-pattern. For example, the selector-max-id rule traverses the AST to count ID selectors and flags any that exceed a limit. With over 100 built-in rules, support for plugins, and shareable configs, it's highly customizable. It can even auto-fix some of the problems it finds.

WHEN TO USE IT Use Stylelint in any project with a CSS codebase of non-trivial size. It is essential for team projects to enforce shared conventions, like naming patterns for custom properties. It's also invaluable for design systems, where it can enforce rules for tokens and component-specific styles. It supports SCSS, Less, and can extract styles from HTML and CSS-in-JS, making it versatile for modern front-end stacks.

WHEN NOT TO USE IT Do not use Stylelint for code formatting tasks like indentation, quote style, or line breaks. While some of its rules overlap with formatting, that job is better suited for a dedicated code formatter like Prettier. Using both tools for their intended purpose is the standard practice. Stylelint is for code quality and conventions; Prettier is for code style and formatting.

ONE CANONICAL EXAMPLE A common configuration is to enforce a design system. You could write a rule to disallow any px value that isn't a multiple of 4, or disallow color hex codes in favor of CSS custom properties (e.g., color: var(--color-primary)). If a developer writes color: #333334;, Stylelint would flag it as an error, enforcing the system and preventing inconsistent one-off values.

Read the original → stylelint.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.