Is there more to optimizing CSS than minimizing character count? - css

I've been reading a lot about jQuery optimization and how you can alter your selectors to cut down on the amount of DOM traversal, but I haven't heard much about CSS optimization outside of the usual minifying process. Is there any way to optimize your CSS loading/processing outside of just reducing character count and server requests?

You can definitely optimise your selectors for performance. One key point is that CSS parsers read selectors right to left, whereas javascript selector engines (like jQuery etc) read them left to right. Basically though, the general principles are the same - you want each piece of the selector to match as few elements as possible, to cut down on the DOM nodes that have to be searched in order to determine a match.
That means, just like javascript, selecting a single, bare id in CSS is the fastest way you can get to an element. Selecting everything *, or selecting based on attributes ([href*=foo]) are among the slowest.
The reading order creates a difference between optimising jQuery selectors and CSS selectors: you don't gain speed by starting with an ID. For example, if you write:
#mainContent ul li
In jQuery, you are starting by finding the element with the ID mainContent, which is very fast, then digging through it's children.
In CSS, though, you are starting with all li elements, then looking to see if they have a ul ancestor, then checking if they're inside #mainContent. Much slower.
Possible gains in speed
You should also know, however, that CSS parsing is much, much faster than javascript DOM traversal - so even when you do have lots of complex, 'slow' selectors, you're unlikely to see a huge gain in performance by optimising them. Here's a good article on the increases in performance: http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/ - the author points out that he could increase rendering time by about 20ms by creating a huge, complex stylesheet and document (6000 DOM elements, and 2000 CSS rules). For a more 'normal' page, your gains would therefore likely be less than 20ms - probably not worth the effort.
My view is that it's good to keep selector performance in mind while you're writing CSS, but don't let it make your stylesheets less readable or maintainable. In the majority of cases, it's not worth optimising an existing stylesheet, unless you can identify some selector that is really unnecessarily slow.
Here is some more good reading on the subject:
http://css-tricks.com/6386-efficiently-rendering-css/
http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors

After reading some of the resources people posted in response to this question I stumbled across this (eleven year old) gem, which is still just as helpful as it was when it was written:
https://developer.mozilla.org/en/Writing_Efficient_CSS
The other big takeaway I found in my research is that you shouldn't sacrifice clean (maintainable) code or semantic best practices for CSS efficiency because the gain is so small. Still, I like my code to be clean AND efficient if at all possible, and the answers here have give me a lot to think about when writing CSS.

Yes, you can make your CSS better in terms of selector matching efficiency. By making your selectors as specific as possible, you reduce the effort needed by the HTML renderer to search the DOM for matching elements.
For example, in the cases where you know that all the spans you want to style will be direct children of the div element within your element with id #thing. it would be faster to do:
#thing > div > span.my-class
than
#thing span.my-class
because that restricts the elements that the selector has to search to find a match.

Merging stylesheets if you have multiple (remember to keep the order right)
You can also host your static content on a different server as your application (a http server optimized for serving static content), like Lighttpd

Related

Is CSS faster when you are specific?

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.

Are nested ids okay if necessary -- performance hit or other?

I'm using a jQuery-based framework (Kendo UI) which comes with its set of highly selective css rules.
In order to avoid the headache of my css rules clashing (and also to avoid using !important all over the place), I've nested everything in a body id -- e.g., #body-id .my-class.
However, is there a performance hit or other issue in using:
#body-id #my-other-id?
Every resource I find says, "it's pointless and makes no sense semantically." I agree, however, as I'm using the Less CSS framework, my entire CSS stylesheet will be wrapped in #body-id (for simplicity sake). Thus, it would eventually compile to #body-id #my-other-id (I'm assuming).
The jQuery selector speed is not very important, because there are other more narrow bottlenecks in your browsers JavaScript implementation.
Only if you have many, many jQuery operations like this to perform, the speed performance will be an issue
But by the way jQuery analyzes the selector (from right to left) an id with child selectors does not profit from javascript getElementById speed.
So it's more or less not important. But it may be not good style.
Check, if your CSS code is modular!
Edit
Here is a 'official' resource on performance and else
http://learn.jquery.com/performance/optimize-selectors/

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)

Resources