CSS - Multiple vs Single class on an element
Is there any performance g开发者_JAVA百科ain in using single css class vs multiples on an element?
Ex:-
<div class="single-class"></div>
vs
<div class="no-padding no-margin some-class some-other-class"></div>
If you have an even moderately complex stylesheet and know what you're doing, using multiple classes has the benefit of taking full advantage of the cascade, which in the end most likely means that your css files will be smaller as you won't be duplicating code. So, in this sense, it actually has a positive impact on performance (dependent on the complexity of your css).
I'm trying to imagine what the jQuery UI stylesheet would look like if it used a one-class-per-element approach. I imagine it would double in size.
Of course like everyone said, the impact is so small you won't notice. Continue your use of multiple classes and embrace the cascade!
FWIW, I really don't like class names like no-padding
, float-left
and ui-corner-all
. Though they make sense to the css author, a semantic approach combined with multiple elements per declaration (to avoid duplicating rules) is almost always preferred. Using the first method, your css will make no sense if you decide that no-padding
actually needs 1px padding, and that a.classname.float-left
actually needs to float right.
Technically, yes fewer classes mean less data transfer for HTML. As far as CSS is concerned, each element needs to be checked against each rule, so fewer classes may mean less matching depending on the rules you have written.
The difference is so small that it's not easily noticeable. You may notice the performance difference if you're populating a page with tens of thousands of elements, but that would be a poor design choice anyway.
One concern I have is with the example you've provided. Your classes no-padding
, no-margin
are descriptive of styles which are a bad idea. If all your some-class
elements also have the no-margin
class, then margin: 0
should be part of the some-class
rule.
Don't add classes for styles, add styles for classes.
The basic rule applies in CSS like in other languages: Don't worry about optimization on this level unless you run into serious actual performance problems, or have tens of thousands of elements. Use what is more readable instead.
There may be differences - using CSS selectors in a sane way is usually extremely un-optimal from a performance standpoint. But compared to other factors, any difference is going to be minuscule.
精彩评论