Reputation: 66
Suppose you have this HTML:
<div class='foo-element-1'></div>
<div class='foo-element-2'></div>
...
<div class='foo-element-500'></div>
CSS:
[class^='foo-'] { font-size: 12px; }
.foo-element-1 { color: red; }
.foo-element-2 { color: blue; }
...
.foo-element-500 { color: green; }
Every .foo-element-###
shares a common style in [class^='foo-']
Another way to write this might be:
HTML:
<div class='foo foo-element-1'></div>
<div class='foo foo-element-2'></div>
...
<div class='foo foo-element-500'></div>
CSS:
.foo { font-size: 12px; }
.foo-element-1 { color: red; }
.foo-element-2 { color: blue; }
...
.foo-element-500 { color: green; }
Nothing else uses .foo
. All .foo-element-###
will have .foo
attached to it in this option. Assume that browser compatibility is a non-factor and there are several hundred of these elements that all have a common style.
Is there a reason in terms of performance or semantics to use one style over the other?
Upvotes: 2
Views: 158
Reputation: 187024
Selection by classes is a good deal faster: http://jsperf.com/class-vs-data-attribute-selector-performance
Also, it just plain makes sense to have elements that share common style to share a common class. And if the elements style must deviate from the shared style, a second class on the element also just makes good sense.
Which means class selectors are both faster and more maintainable. There's not much downside here, other slightly more verbose markup. But assuming you are generating these items in a loop in some templating language, you would only need to write that extra class value once and the loop would duplicate it.
So yeah, use the class selector. It's pretty sweet.
Upvotes: 2