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 */
}
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 */
}
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 */
}
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>
which is not really good for maintainability.
So, as an experienced developer how you deal with this dilemma?
Top comments (2)
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.
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:
I created a common class
.heading
and gave itfont-weight: 700;
Thanks for your participation on this.