Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance gain from specifying element.class { ... } vs just .class { ... }?

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?

like image 946
chrickso Avatar asked Aug 30 '12 16:08

chrickso


People also ask

Which selector is faster ID or class?

Locating elements by id is faster than css. Because : id of an elements is more specific than css of an element.

Which is the faster ID or CSS?

Is ID faster than class CSS? Since IDs are the first actions to be resolved, technically, they are faster.

How to style an entire class in CSS?

If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size.

How do you choose a class element?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.


1 Answers

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.

like image 100
jackwanders Avatar answered Oct 20 '22 01:10

jackwanders