Is having a long CSS selector bad? - css

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

Related

Nested selectors performance impact and LESS

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).

CSS selector performance

I know the performance difference is miniscule, but which is a faster CSS selector?
div.class{ }
or
.class{ }
CSS Selectors are parsed right to left, and then displayed, and the full rule is always parsed. So that would lead me to believe that .class is slightly quicker than div.class. That said, there's also the time taken to render the page, so it may depend on how many elements have that class and how complex the rule is.
Now with all of that said, check out the first answer here: https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil
The performance difference is so minuscule (if detectable at all) that it's not worth even thinking about.
Use div.class if you need some styles to only apply to div elements with that class, use .class otherwise. Base your decision on what your styling needs are, not some infinitesimal performance benefit.
Note: There are some selectors that really are (relatively) slow and might be worth changing, things like .class > *. But, even for selectors with really bad performance, and even if you're at a reasonable stage in your project to start thinking about optimizing things, there are exactly a million things you should worry about first before you get to CSS selector optimization.
I think it may depend on browser, you can check selectors here:
http://jsperf.com/jquery-performance-bn/3
In my browser (Opera 11.62) div.class was a lot faster.
.class {} selector is faster than div.class {} because in the first case browser only checks that the element has specified class, whereas in the second case it additionally has to check the element is actually a div.
I don't even remember asking this question at this point, but here's the jist:
The performance difference is minute, EXCEPT when using a JS library like jQuery. To evaluate $('.class'), jQuery checks all elements in the DOM. To evaluate $('div.class'), it only checks divs. So depending on the size of the DOM and the elements in it, the performance difference can be pretty significant.
So really, the pure CSS performance is almost exactly the same, but performance when run though a Javascript selector engine can be noticeably different. I think that is what I was aiming for when I asked this. Thanks to everyone for your comments, you all get upvotes :)

Are CSS selectors a big performance hit?

I have a web application with bunch of HTML code. There are some style-attributes that I can't get rid of, but I was wondering if it's worth the cleanness to get rid of class-names and use CSS selectors instead. Do CSS selectors perform slowly?
I'm talking about replacing class-name selectors such as .example with more complex selectors like #example div > div:nth-child(3) > p
Take a look at this article to see a graph on this. I don't know how exact this benchmark is, but it seems child selectors are indeed slower, but you're not going to find any visible gains by avoiding child selectors.. this is a micro optimization that has "diminishing returns" written all over it.
The performance hit is tiny.
Here you can find an interesting blog post on the argument with examples and tests of CSS selectors performances on most common browsers:
http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/
This is the conclusion of the author:
Based on these tests I have the
following hypothesis: For most web
sites, the possible performance gains
from optimizing CSS selectors will be
small, and are not worth the costs.
There are some types of CSS rules and
interactions with JavaScript that can
make a page noticeably slower. This is
where the focus should be.
The browser matches from right to left, and any non-specific tags will cause more of a performance hit.*
1–Slower:
.foo p
2–Faster
.foo p.bar
What happens is in the first example, the browser matches ALL paragraphs, then narrows it down to those whose ancestor has the foo class.
In the second example, the browser matches all elements that have the bar class, then matches the subset that are paragraphs, then the subset whose ancestor has the foo class.
One would generally expect the initial set of the second example to be smaller than that of the first example.
*Bear in mind that the hit will really only become apparent with poorly-crafted CSS on pages that are very large (megs) and/or have many, many elements (e.g., hundreds of spans or divs). Small pages with only a few number of elements will not see a real—if any—performance hit, even with poorly-written CSS.

Is there an advantage to using very specific selectors in CSS?

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)

CSS Selector Style

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.

Resources