CSS Selector Chain Performance

2019-07-22 20:50发布

问题:

I will try to explain my question with a little bit of CSS

Option 1

I don't repeat the float:left; all over the place, instead I chain all the class names that are going to float left together.

 .one-little-thing,
 .two-little-things,
 .three-little-things,
 .four-little-things,
 .five-little-things {
    float:left;
}
.one-little-thing {
    color: blue;
}
.two-little-things {
    color: red;
}
.three-little-things {
    color: yellow;
}
.four-little-things {
    color: blue;
}
.five-little-things {
    color: green;
}

Total Number of Characters: 331 (including spaces, but even if you trim the spaces, the example is going to be valid)

Option 2

  • Where I repeat float:left; all over the place, but I get slightly less characters.
.one-little-thing {
    color: blue;
    float:left;
}
.two-little-things {
    color: red;
    float:left;
}
.three-little-things {
    color: yellow;
    float:left;
}
.four-little-things {
    color: blue;
    float:left;
}
.five-little-things {
    color: green;
    float:left;
}

Total Number of Characters: 284

I did exactly the same thing with both pieces of code here, the second way has less characters, which means less bytes.

So my question is this:
Does this mean that the second way is better for performance ? What if I had up to ninety-nine-little-things ?

Why it concerns me
The @extend in Sass allows to for example to @extend .clearfix;, which, if used as in "Option 1" would result in a very, very long selector.

So which is the best way ?

回答1:

With such a minimal difference in characters the performance result will obviously not be noticeable here. However, The benefit of writing CSS the way you did in the first snippet is that you could add a lot of other shared properties in only one place and have them applied to each of the classes. As you add more and more shared properties you will see the character difference tip in favor of the first method.

Also, say you decided to translate your site to support hebrew or another RTL language. All you would have to do is change the float: left to float: right in that one spot instead of each individual class. With that said, I think its important to look at CSS from a usability and longterm scalability perspective instead of pure server performance at a particular instance.