Performance when specifying element.class {...} vs just.class {...}?

If I know that a particular class will be used only for div or p, is there even the slightest effect on performance by specifying div.class or p.class, and not just .class?

+4
source share
3 answers

If you're interested in checking this out yourself, Steve Souders has a โ€œCSS Test Creatorโ€ that allows you to check the speed of various 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. Performing 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 works a little faster, but not significantly (37 ms more than 10000 elements). However, there is a reason to use .class over tag.class , and thatโ€™s flexibility. If you have a group of <div class="content"> elements that you later change to <section class="content"> elements, you will have to change your CSS if you used div.content rules. If you used .content then CSS updates are not needed.

In general, I would only use the tag.class style selector if you have several types of tags that use the same class and you want to target only a specific type of tag.

+5
source

Yes .class little faster than element.class . This is because CSS is read from left to right, therefore .class means ("Match all elements that have a class name .class "), and element.class means ("Match all elements that have a class name .class , which also are element ").

However, element.class will have a higher specificity value than .class .

0
source

I know this is not a question, but it affects specificity, so in the example below, innerClassFails does not override the contained tds, and table.innerClass overrides 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> 
0
source

All Articles