Course contentsShow
← Web Development
Lesson 1440 of 2,98226. Code Quality ToolsFree lesson

Enforcing Naming Conventions

Using rules like selector-class-pattern to enforce BEM, kebab-case, or custom naming patterns.

Enforcing Naming Conventions

You'll learn how to use Stylelint's pattern-matching rules to automatically enforce consistent CSS naming conventions like BEM or kebab-case across your codebase.

Why Naming Conventions Matter

Imagine a project where every developer names classes however they feel that day: myButton, My-Button, my_button, MyButton. The chaos makes code hard to read and maintain. Stylelint can act as an automatic referee, ensuring everyone follows the same naming rules.

The selector-class-pattern Rule

Stylelint provides a powerful rule called selector-class-pattern that validates class names against a regular expression pattern. This lets you enforce methodologies like BEM (Block Element Modifier) or simpler patterns like kebab-case.

Kebab-case example:

{
  "rules": {
    "selector-class-pattern": "^[a-z][a-z0-9]*(-[a-z0-9]+)*$"
  }
}

This pattern allows button, nav-menu, and card-header-title, but rejects myButton or My_Button.

BEM pattern example:

{
  "rules": {
    "selector-class-pattern": "^[a-z]+(__[a-z]+)?(--[a-z]+)?$"
  }
}

This enforces block, block__element, and block--modifier structure, rejecting anything that doesn't follow BEM.

Custom Messages

You can provide helpful error messages when patterns fail:

{
  "rules": {
    "selector-class-pattern": [
      "^[a-z][a-z0-9]*(-[a-z0-9]+)*$",
      {
        "message": "Class names must use kebab-case (e.g., my-class-name)"
      }
    ]
  }
}

Key Takeaway: Using selector-class-pattern and similar Stylelint rules automatically enforces naming conventions, preventing inconsistencies before they reach your codebase and making your CSS predictable and maintainable.