I was wondering what impact on parsing and rendering performance may have to group rules in CSS.
Approach 1:
.class1 {
margin: 10px;
padding: 20px;
color: #ccc;
}
.class2 {
margin: 10px;
padding: 30px;
color: #ddd;
}
.class3 {
margin: 20px;
padding: 30px;
color: #eee;
}
.class4 {
margin: 20px;
padding: 20px;
color: #fff;
}
vs approach2:
.class1,
.class2 {
margin: 10px;
}
.class3,
.class4 {
margin: 20px;
}
.class1,
.class4 {
padding: 20px;
}
.class2,
.class3 {
padding: 30px;
}
.class1 {
color: #ccc;
}
.class2 {
color: #ddd;
}
.class3 {
color: #eee;
}
.class4 {
color: #fff;
}
Of course, we are talking about large css files with same rules grouping, so the same selector is fragmented into plenty of chunks sometimes.
Does it impact css parsing and rendering significantly enough to abandon this approach in favour of bigger file, but cleaner and gathering all rules in one selector?
Selector matching may be expensive. In real life case, each of those selectors is not just one class, but 2-3 nested classes. So for each element browser has to match selector three times to apply all rules. First for margin, then for padding, then apply color. The second approach seems very expensive.