CSS: #id .class VS .class performance. Which is better?
CSS selectors are matched from right to left.
Therefore, .videoContainer
should be "faster" than #dialog .videoContainer
because it misses out testing for #dialog
.
However, this is all irrelevant at best - you'll never notice the difference. For normally sized pages, the amount of time we're talking about is so insignificant as to be nonexistent.
Here's a relevant answer by an expert that you should read: Why do browsers match CSS selectors from right to left?
CSS Performance, #id vs .class vs [^regex$] vs selector
Per Eoin's request, I'm making an answer for future visitors (as I think this is useful).
From this link: https://www.sitepoint.com/optimizing-css-id-selectors-and-other-myths/
The following snippet runs on 50,000 nodes. The console output will give you an answer on performance for specific selectors.
const createFragment = html => document.createRange().createContextualFragment(html);
const btn = document.querySelector(".btn");const container = document.querySelector(".box-container");const count = 50000;const selectors = [ "div", ".box", ".box > .title", ".box .title", ".box ~ .box", ".box + .box", ".box:last-of-type", ".box:nth-of-type(2n - 1)", ".box:not(:last-of-type)", ".box:not(:empty):last-of-type .title", ".box:nth-last-child(n+6) ~ div",
];let domString = "";
const box = count => `<div class="box"> <div class="title">${count}</div></div>`;
btn.addEventListener("click", () => { console.log('-----\n'); selectors.forEach(selector => { console.time(selector); document.querySelectorAll(selector); console.timeEnd(selector); });});
for (let i = 0; i < count; i++) { domString += box(i + 1);}
container.append(createFragment(domString));
body { font-family: sans-serif;}
* { box-sizing: border-box;}
.btn { background: #000; display: block; appearance: none; margin: 20px auto; color: #FFF; font-size: 24px; border: none; border-radius: 5px; padding: 10px 20px;}
.box-container { background: #E0E0E0; display: flex; flex-wrap: wrap;}
.box { background: #FFF; padding: 10px; width: 25%}
<button class="btn">Measure</button><div class="box-container"></div>
CSS Optimization: Element ID vs. Class
- IDs are the fastest
- Tag names are next fastest
- Class names with no tag name are the slowest
As for which one to use, use whichever is most appropriate. If you have a search box on your page then using an ID for that would be most appropriate because there's only one search box. Table rows on the other hand will probably be identified by class because there is (or can be) more than one.
Try not to use selectors (in CSS or jQuery) like ".class". You're forcing jQuery or the browser to basically traverse the entire document tree. Most of the time the class will only apply to one kind of tag so specify that (eg "div.class"). That alone can make a huge performance difference (particularly on jQuery with a large document).
The length of the selector should not be a consideration. Performance, readability and maintainability should be.
CSS Performance between class and attribute selectors
There is no performance issue. Both act same. But there is difference in specificity of the css with class versus Elements.
Specificity - Specificity determines, which CSS rule is applied by browsers.
If two selectors apply to the same element, the one with higher specificity wins.
But specificity has hierarchy.
- Inline styles (Presence of style in document).
An inline style lives within your XHTML document. It is attached directly to the element to be styled. E.g. - IDs (# of ID selectors)
ID is an identifier for your page elements, such as #div. - Classes, attributes and pseudo-classes (# of class selectors).
This group includes .classes, [attributes] and pseudo-classes such as :hover, :focus etc. - Elements and pseudo-elements (# of Element (type) selectors).
Including for instance :before and :after.
Source: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
Hence div.test {}
is more specific.
Whats the difference between using .Class or #ElementId in CSS?
An ID must be unique in a document. Classes can be used in any number and combination. So you can use one class on multiple elements and multiple classes on one element.
What's the difference between an id and a class?
ids
must be unique where as class
can be applied to many things. In CSS, id
s look like #elementID
and class
elements look like .someClass
In general, use id
whenever you want to refer to a specific element and class
when you have a number of things that are all alike. For instance, common id
elements are things like header
, footer
, sidebar
. Common class
elements are things like highlight
or external-link
.
It's a good idea to read up on the cascade and understand the precedence assigned to various selectors: http://www.w3.org/TR/CSS2/cascade.html
The most basic precedence you should understand, however, is that id
selectors take precedence over class
selectors. If you had this:
<p id="intro" class="foo">Hello!</p>
and:
#intro { color: red }
.foo { color: blue }
The text would be red because the id
selector takes precedence over the class
selector.
Should I aim to add a class/id to everything, or use other selectors
There's no hard and fast answer here.
A general rule of thumb might be to use classes when you want to group certain elements together, treat them the same and using a class is the only means of doing it.
In your last example for instance, there is strictly no need for a class.
But, using a class in example 3 will result in better performance, as the browser will located the relevant items quicker. Traded off against this is a slight reduction in code-legibility..
If you have class names on everything then it becomes harder to read the rest of the markup.
In short, in what you have shown above, what you have written is fine imo.
You should read this article though which covers selector efficiency.
Basically the order of efficiency is as follows:
ID, e.g. #header
Class, e.g. .promo
Type, e.g. div
Adjacent sibling, e.g. h2 + p
Child, e.g. li > ul
Descendant, e.g. ul a
Universal, i.e. *
Attribute, e.g. [type="text"]
Pseudo-classes/-elements, e.g. a:hover
The performance difference between classes and Id's is normally irrelevant.
Going further down the list though, things slow down considerably.
This isn't an argument to add classes and id's everywhere - it just allows you to judge the trade-off between performance and maintainability.
Related Topics
How to Change Font-Size of a Tag Using Inline CSS
Refinerycms 2.1.0 and Zurb 4 Top Menu with Dropdown Navigation
Unbalanced CSS Columns in Chrome
Disable HTML5 Video Download at CSS Breakpoint
Webkit-Font-Smoothing: Suddenly Different Results in Chrome and Safari
Flexbox Align Items Horizontally
Force Nested Divs to Have Min-Height of 100%
Make Element Width Stretch to Fit Its Children When Element's Parent Has Overflow: Auto;
Stop Div Resizing Parent Div Using CSS
How to Center Text Inside: Before Pseudo Element
How to Specify Image Paths in CSS Files
How to Make a Blinking Image in CSS3
CSS: Nth-Of-Type() and: Not() Selector
How to Give Class Name to Animation State in Angular 2/4
CSS Animate a Div with Absolute Positioning from Left 0 to Right 0