DEV Community

Cover image for CSS: Selector vs declaration duplication dilemma
Ahmad Khalid
Ahmad Khalid

Posted on • Updated on

CSS: Selector vs declaration duplication dilemma

If you used CSS analyzer tools e.g. CSS Analyzer by Project Wallace you may have noticed the relation between selector duplication and declaration duplication.

Let's say we want to apply a padding of 1rem to three different selectors then we have multiple choices:

Choice one: Repeat the declaration for all selectors

.selector1 {
  /* other declarations */
  padding: 1rem;
}

.selector2 {
  /* other declarations */
  padding: 1rem;
}

.selector3 {
  padding: 1rem;
  /* other declarations */
}
Enter fullscreen mode Exit fullscreen mode

Result: Higher declaration duplication score and higher declarations per ruleset.

Choice two: Combine selectors that share the same declaration

.selector1,
.selector2,
.selector3 {
  padding: 1rem;
}

.selector1 {
  /* other declarations */
}

.selector2 {
  /* other declarations */
}

.selector3 {
  /* other declarations */
}
Enter fullscreen mode Exit fullscreen mode

Result: lower declaration duplication but higher selector duplication.

Choice three: Using of utility classes

.padding-1rem {
  padding: 1rem;
}

.selector1 {
  /* other declarations */
}

.selector2 {
  /* other declarations */
}

.selector3 {
  /* other declarations */
}
Enter fullscreen mode Exit fullscreen mode

Result: lower score of both selector and declaration duplications but it violates the Separation of concerns concept and we end up with markup like this:

<p class="padding-1rem margin-0 text-bold text-center etc">...</p>
Enter fullscreen mode Exit fullscreen mode

which is not really good for maintainability.
So, as an experienced developer how you deal with this dilemma?

Top comments (2)

Collapse
 
alohci profile image
Nicholas Stimpson • Edited

It depends on the HTML document content semantics. If the same padding is chosen because the content of each has an identical classification, give the elements a common class that describes that semantic classification (not a utility class) and bind the declaration block to a single complex selector that uses that class. If the same padding is chosen because of a similarity in the classifications of each, select option 2. If the same padding is chosen coincidentally, select option 1. This strategy will simplify future maintenance.

Collapse
 
ahmadkdev profile image
Ahmad Khalid

Firstly I'm sorry for late reply. I like your strategy and I already used the common class technique in one situation so instead of:

.heading-xl {
  font-weight: 700;
  /* other declarations */
}

.heading-l {
  font-weight: 700;
  /* other declarations */
}
Enter fullscreen mode Exit fullscreen mode

I created a common class .heading and gave it font-weight: 700;

Thanks for your participation on this.