Sheath rule
best-practices-no-duplicate-class
Disallow duplicate class names in the
class attribute.
- Package
- Core
- Category
- Best Practices
- Default severity
- warning by default
- Auto-fix
- Auto-fix available
#Why
Duplicate class names are unnecessary and can indicate copy-paste errors or confusion about what styles are applied. While browsers handle duplicates gracefully, they add noise to the code.
#Examples
#Bad
<!-- Duplicate class name -->
<div class="container container">Content</div>
<!-- Duplicate among multiple classes -->
<button class="btn btn-primary btn btn-large">Click</button>
#Good
<!-- Each class appears once -->
<div class="container">Content</div>
<!-- Multiple unique classes -->
<button class="btn btn-primary btn-large">Click</button>
<!-- No duplicates -->
<div class="card card-large">Content</div>
<!-- Class tokens are case-sensitive -->
<div class="Card card">Content</div>
#Auto-fix
The fixer removes duplicate class names, keeping the first occurrence:
<!-- Before -->
<div class="container wrapper container">
<!-- After -->
<div class="container wrapper">
The fix applies only to static attributes. Attributes containing echoes or directives are reported without a fix.
#Blade in the class Attribute
A class attribute in Blade is usually stitched together from literal text and
constructs that emit more of it. Only names that whitespace bounds on both sides
count, so a name a Blade construct completes is left alone:
{{-- Two classes, neither of them known until render. Not duplicates. --}}
<div class="{{ $a }} {{ $b }}"></div>
{{-- One class whose name ends in an echo. `btn-` is not a class name. --}}
<div class="btn-{{ $size }} btn-{{ $size }}"></div>
{{-- Both branches name the same classes, but only one of them ever renders. --}}
<div class="{{ $mobile ? 'text-xs font-mono' : 'text-xs font-mono' }}"></div>
{{-- `card` really is there twice, whatever $modifier renders. Reported. --}}
<div class="card {{ $modifier }} card"></div>
#Notes
- Class comparison is case-sensitive, matching CSS selector behavior (
Cardandcardare distinct) - The order of remaining classes is preserved, as is the quote style
- Utility-class frameworks can introduce duplicates when classes arrive from several places at once
#References
- HTML Spec: Class Attribute - The class attribute specification
- MDN: class Attribute - Documentation on the class attribute
#Related Rules
- best-practices-no-duplicate-attrs - No duplicate attributes