Reputation: 3034
If I know a particular class will only be used on div's or p's, is there even the slightest effect on performance by specifying div.class or p.class instead of just .class?
Upvotes: 7
Views: 2137
Reputation: 1861
I know this was not the question, but it affects specificity, so in the example below, the innerClassFails doesn't override the contained tds, while the table.innerClass does override it.
<style>
table.outerClass td {
color: red;
}
table.innerClass td {
color: green;
}
.innerClassFails td {
color: green;
}
</style>
<table class='outerClass'><tr><td><table class='innerClass'><tr><td>Hello!</td></tr></table></td></tr></table>
<table class='outerClass'><tr><td><table class='innerClassFails'><tr><td>Hello!</td></tr></table></td></tr></table>
Upvotes: 0
Reputation: 16050
If you're interested in testing this yourself, Steve Souders has a "CSS Test Creator" which lets you test the speed of different CSS selectors:
http://stevesouders.com/efws/css-selectors/csscreate.php
I tested both .class
and a.class
using 10,000 rules and 10,000 anchors. Running each test 5 times, I got the following results:
+----------+-----------+----------+
| Test # | a.class | .class |
+----------+-----------+----------+
| 1 | 2915 ms | 2699 ms |
| 2 | 3021 ms | 2869 ms |
| 3 | 2887 ms | 3033 ms |
| 4 | 2990 ms | 3035 ms |
| 5 | 2987 ms | 2980 ms |
+----------+-----------+----------+
| AVERAGE | 2960 ms | 2923 ms |
+----------+-----------+----------+
As you can see, .class
is slightly faster, but insignificantly so (37ms over 10,000 elements). However, there is a reason to use .class
over tag.class
, and that is flexibility. If you have a bunch of <div class="content">
elements that you later change to <section class="content">
elements, you'll have to modify your CSS if you used div.content
rules. If you used .content
, then no CSS updates are needed.
In general, I would only use tag.class
style selectors if you have multiple tag types that use the same class, and you only want to target a specific tag type.
Upvotes: 9
Reputation: 175098
Yes, .class
is slightly faster than element.class
. That's because CSS is read left to right, so .class
means ("Match all the elements who have class name of .class
") while element.class
means ("Match all the elements who have a class name of .class
who are also an element
").
However, element.class
will have a higher specificity value than .class
.
Upvotes: 0