Enforcing Naming Conventions with Linters
You'll learn how to automatically validate BEM naming conventions using Stylelint to ensure your entire team writes consistent CSS.
The Problem: Manual Checking Doesn't Scale
You've learned BEM conventions like block__element--modifier, but what happens when multiple developers work on the same project? Someone might accidentally write block_element (single underscore) or block-modifier (single hyphen), breaking the pattern. Manually checking every class name is tedious and error-prone.
Stylelint: Your CSS Quality Guardian
Stylelint is a linter—a tool that automatically checks your CSS code against rules you configure. Think of it as spell-check, but for your CSS naming conventions. It catches mistakes before they reach production.
Configuring BEM Validation Rules
In your Stylelint configuration file, you can add rules that enforce BEM syntax:
// .stylelintrc.json
{
"plugins": ["stylelint-selector-bem-pattern"],
"rules": {
"plugin/selector-bem-pattern": {
"preset": "bem",
"componentSelectors": "^[a-z]+(-[a-z]+)*(__[a-z]+(-[a-z]+)*)?(--[a-z]+(-[a-z]+)*)?$"
}
}
}
This regex pattern ensures:
- Block names: lowercase with single hyphens (
button,nav-menu) - Elements: double underscores (
button__icon) - Modifiers: double hyphens (
button--primary)
Catching Mistakes Automatically
When someone writes .card_title instead of .card__title, Stylelint immediately flags it during development or in your CI/CD pipeline. No more guessing, no more inconsistency across team members.
Key Takeaway: Stylelint enforces BEM naming conventions automatically through configurable rules, ensuring every developer follows the same patterns without manual review—making your codebase consistent and maintainable at scale.