Lets imagine very simple case:
div.className{}
vs
.className{}
Which option is faster and why ?
The difference between Class and ID selectorIDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.
Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)
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. To do this, start with the element name, then write the period (.)
.className{}
is faster in downloading, because of smaller size of the css file.
It is also faster when rendering page, because it is not necessary to look for div
elements.
A guideline from google:
Avoid qualifying ID and class names with type selectors. Unless necessary (for example with helper classes), do not use element names in conjunction with IDs or classes.
Avoiding unnecessary ancestor selectors is useful for performance reasons .
One very important difference between div.classname
and simply .classname
is in something called selector specificity. It is a set of rules which defines which selector gets more weight once the browser starts going through all the selectors that potentially have influence on a particular element.
ne of the most basic rules of CSS is that selectors can be redefined in a way that whatever definition comes last and has influence on a particular element its the one that is going to be used (the sole exception being when using !important which always takes precedence).
Now in the above example redefining the .class selector should actually hide the text but instead its still visible. How is that possible if we said that latter rules always take precedence? Its because the div.classname rule has a higher specificity that .box since it actually gets points for containing both an element (div) and a class selector (.class) in its selector declaration (div.class).
Of course the div.class rule will be applied only on a div element but since class selectors are often reusable pieces of code there is plenty of situations when they are used on divs.
Although the rules in the official W3 specification are not that hard to understand they are sometimes pretty hard to remember. That's why I would like to recommend an excellent article on CSS selector specificity which can be found here.
In my opinion selector specificity is by far the most important thing to master when it comes to tracing inheritance problems with CSS stylesheets.
For Example
Find some more info
Follow Up
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With