Thursday, July 28, 2011

High Performance CSS

Recently I looked at some people's code, and found out this css rule.

table.captain tbody tr td input[type="text"] { ... }

Do you see anything wrong here??  Well, not wrong, it is still valid and running fine. But in terms of efficiency, this one could not be very good. Why??  Please first read the following and try to understand how browser engine parse your css.

The browser render your css from left to right, and when it hit each "parent", it will asked a question "Does it match or not match?".  So the longer your rule is, the less efficient it will be.

Let me translate how the browser filter or render your css above.

1) input[type="text"] | Is there anything matched?  Yes, go to next step

2) Is the above element contained in a "td"? Yes, go to next step

3) Is the above element contained in a "tr"? Yes, go to the next step

... blah ...

And if you plan to write efficient (or high performance) css, you should first ask yourself a question:  Do I need all those category or selectors?  Can I simplify it and still get the results?  In other words, are the rules all necessary?

How about if I rewrote the above rules like the following?

table.captain td input[type="text"] { ... }

or even this one

.captain td input[type="text"] { ... }

Any of these rules will be much faster than the first one.

There is a good blog entry about Efficient use of css -


  1. .captain td input[type="text"] might not be correct, e.g., if there is a div with class captain and within it it has a table (not with class captain) with a cell having a text type input, this rule will match incorrectly.

  2. Of course, it depends on your use case ( for example, the markup that u've mentioned ), but the point is to simplify if possible.