I have been reading for the past 1.5 hours about this and still couldn't find a concise and decisive answer.
As far as I understood browsers parse CSS selectors from right to left.
That means a long CSS selector such as this:
.card .container .businesscard .pinfo li.pinfo-box span:first-child
is one of the least efficient lines of code to ever appear here in SO.
First of all, am I right on this one?
Secondly, I am designing a rich UI using LESS, which ultimately produces this kind of mammoth selectors out of the nested designs I am coding.
What can be done to avoid this kind of selectors? Rely on classes and IDs alone? But then again what is the purpose of using LESS if you can't write nested CSS?
Your input is appreciated.
That is correct. Browsers evaluate selectors from right to left. It will try to find a span inside a li.pinfo-box and so on.
One rule of thumb to folllow when writing LESS is: do not nest more than 3-4 levels.
This will prevent your selectors from growing to big, while you will still be able to benefit from the nesting feature in LESS.
A good example of "useless" nesting is when styling lists. Sometimes I write the selectors like this:
#wrapper .blog-post ul, #wrapper .blog-post ul li
Is it really necessary to specify that the li must be inside a ul? It will probably be enough writing:
#wrapper .blog-post li
All of this is good to know. BUT: This is not the first thing to dive into when trying to optimize your sites performance. Spend some time lower the number of request or something else instead.
Selector parsing and matching is unlikely to be a big factor unless you have pretty unusual content. I would suggest using whatever is maintainable and gets the job done, up until the point where testing shows a performance issue. Then I'd get out a profiler (on OSX I'd use Instruments, but there should be a decent one available for most platforms) and attach it to the browser; if selector matching shows up high on the profile, then look into replacing slow selectors with faster ones (id selectors are definitely a good bet).
Related
Is div.container faster than .container ?
You know like in jquery if you be more specific with your selectors it is faster since it iterates through less.. Is this the case with css ?
Is there a way to measure performance in css ?
Performance wise, does things like this even matter or does it all depend on text weight basically ?
I'd be happy if someone knows the answer to it, I've actually found a similar question with no certain answer.
Can CSS be more efficient if it is better specified?
In real world the speed difference would be negligible.
To be technical .container would be faster as it has fewer selectors to process.
Selectors have an inherent efficiency. The order of more to less efficient CSS selectors goes thus:
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
In regards to your second question:
Is there a way to measure performance in CSS ?
Steve Souders put out an online test to measure performance of CSS that can still be accessed here.
There are better ways to measure performance nowadays, but this is a quick and easy resource you can play with.
Performance wise, does things like this even matter or does it all depend on text weight basically ?
The short answer is "not really".
The long answer is, "it depends". If you are working on a simple site there is really no point to make a fuss about CSS performance other than general knowledge you may gain from best practices.
If you are creating a site with tens of thousands of DOM elements then yes, it will matter.
delta between the best case and the worst case was 50ms. In other words, consider selector performance but don’t waste too much time on it.
See: https://smacss.com/book/selectors
So I do not think it makes much sense to extend CSS rules ONLY to get a higher performance. Just consider the higher amount of network traffic, maybe worse maintainability, ...
However in the link you can read, which rules to consider without having to increase the CSS size.
If .container and div.container match exactly the same elements on your page, the first one might be even faster: If the browser evaluates .container at first, actually it would have been finished, but with div.container it has ADDITIONALLY to check, whether the element is a div.
disclaimer: I do not know how browsers really implement these things. My conclusions are based on the linked article.
Generally, the fewer the rules the better, so .container would be faster than div.container. Apart from caching, the .container gets read first, then other elements have to have the div added on as a second-level filter... unnecessary in many circumstances.
This is pretty common across engine, though there are some minor deltas.
See this article: Writing efficient CSS, which although it is from MDN (and is therefore Mozilla-geared) holds true for most of what I know about the engines in general.
Is a selector like
.a, .b, .c, .d, .e, .f, .g, .h, ......... , .zzzzz {font-size:16px}
bad for performance? If yes how and if no why?
I Googled and read a lot of posts including the ones by Mozilla and couldn't find any mention of having a large number of class names as a selector being bad.
No, there is no performance problem here.
What is bad is a long selector involving many checks but your selector is in fact a sequence of selectors, equivalent to
.a {font-size:16px}
.b {font-size:16px}
...
Selectors with just a class are among the most efficient ones.
There's no real problem, even if you probably should have less classes in order to manage your code more easily.
This is the valid syntax for assigning a common properties to multiple classes at a time. there is no down side effect.
Saving a single bite is good. Yup as #dystroy said it's doesn't impact that much on your page performance but it's not a good coding particle & also it's hard to manage your code.
Write like this:
body{font-size:16px}
You didn't choose a large selector, you just assigned many selectors to your stylesheet. A large selector would be for example:
header nav ul li a
As the browser uses selectors from right to left the key-selector (the last selector in line, in this example the anchor-element a) is too general. When beginning to render the style the browser begins to grab for all elements according to the key-selector, what would probably mean, that it got much more elements, as effectively needed. In this example it would be much better, if navigation items get unique classes, so the stylesheet must only be applied to following selector:
.primary-link
So, it's import the right key-selector for your styles, to reduce the rendering time to a minimum.
If you want to read something interesting about CSS selectors and performance I can recommend that page: http://learn.shayhowe.com/advanced-html-css/performance-organization
I usually prefer Sass over CSS and one big reason is it allows me to write nested rules, which often reduces the amount of code I write.
I wonder, however, if there is any drawbacks of the idea. What could become problematic when writing nested CSS code?
You should only be as specific as you need to be with CSS - it's very easy to get carried away and end up with selectors like div#body #content #sidebar ul.results li a, which is a) horrible to read, b) slower for the browser to interpret, and c) nearly impossible to override if you need to.
I think debugging will be little difficult while using SASS or LESS
I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.
Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?
This is true in CSS -
A good rule is to descend from the nearest ID.
IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.
Google Code- Optimize browser rendering
This answered a lot of questions I had on the subject including this one-
I hope you find it useful.
Read up on css specificity - which is the most important reason to be more or less specific with your css.
http://www.w3.org/TR/CSS2/cascade.html#specificity
As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.
Edit
This looks like a bit of a duplicate:
CSS Performance Question
it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.
This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.
As far as I know, how specific your selectors are make very little difference on the performance.
The two areas where more specific selectors are most useful, is to reduce the risk that it's not applied where you don't want it, and to make one selector take precedence over another.
A more specific rule has precedence over a less specific rule, so:
span.myclass {}
has precedence over:
.myclass {}
(no matter what the order is in which the rules were declared)
I didn't see anything on here about it with a quick search, if there is let me know.
Here is an example of a CSS selector I'd write.
div#container div#h h1 { /* styles */ }
div#container div#h ul#navi { /* styles */ }
div#container div#h ul#navi li.selected { /* styles */ }
I write all my CSS like. This allows me to stop from having styles floating around and I can technically re-use the same class name easily. For instance, I might use .selected on multiple elements across the site.
I also specify the element type (div, ul, etc) before the class/id unless the style is used for multiple elements. I also specify the element before id's even though there will only ever be one id because it allows me to know the element easily when reading my CSS. For instance I'll know right off the bat that em#example will most likely have a font-style of italic.
This isn't a question about CSS formating, it's about writing selectors.
I'd love to hear opinions on this approach, as I've used it for years and I'm reevaluating my stying.
Although it's somewhat off topic I also write my selectors like this for selector libraries (like jQuery for instance). Although I haven't looked into jQuery's internals to see if there is performance issue with specifying the element with an ID.
I think it really depends on what the selector is for.
Almost every site has one or a few style sheets that "skin" the site - fonts, text colour, link colour/hover, line spacing, and so on, and you don't want these selectors to be very specific. Similarly, if you have a component or element that's reused in many pages and always needs to look the same - like let's say the tags right here on SO - then it's going to be a pain to maintain if you use selectors based on the ID.
I would always use the ID in the selector if it refers to a specific element on a specific page. Nothing's more frustrating than trying to figure out why your rules don't seem to be working because of a conflict with some other rule, which can happen a lot if everything is classes. On the other hand, I think that nesting the IDs as you are (#container #h) is redundant, because the purpose of an ID is to be unique. If you have more than one element with the same ID on the same page then you can end up with all sorts of problems.
It does make the CSS slightly easier to understand when your selectors provide some idea of the "structure" that's being represented, but, to be honest, I think that goes against the idea of separation of concerns. The #navi might be moved outside the #h for perfectly legitimate reasons, and now somebody has to update the style sheet for #navi, even though nothing about it has changed.
A bit subjective as Darrell pointed out but that's my two cents.
While the question is a little subjective I have to say I agree with your thinking. I think defining the element before the selector is clearer when reading the code and it is less error prone.