5

When defining CSS for a particular element does specifying exact path make any difference when we are talking about speed/accuracy/processing of a web page?

for e.g. if I have text inputs ONLY in 3rd column of my table, which is better for speed, accuracy, processing and other parameters?

OPTION 1:

table input[type="text"]
{
    background:yellow;
}

OPTION 2:

table td:nth-child(3) input[type="text"]
{
    background:yellow;
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Nikunj Madhogaria
  • 2,139
  • 2
  • 23
  • 40

1 Answers1

7

No, adding more compound selectors just gives the browser more elements to check and thus more work to do.

If the inputs will only ever appear in a specific place and you can guarantee that they will never appear anywhere else in a given page, then however precise you make your selector beyond input[type="text"] is irrelevant because it will always target the same set of elements anyway. Any extra checks you add then become redundant.

But the real question is whether performance even matters here. Unless you have tens of thousands of such elements, chances are the answer is no. Be as specific as you feel comfortable with. If you need the contextual selectors to make sure you don't accidentally target the wrong elements, there is no harm in putting them in.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • In case of 2nd option, isn't it most likely that the browser doesn't need to search for text inputs in columns other than 3rd column? – Nikunj Madhogaria Sep 16 '14 at 13:02
  • 3
    @nikunj: It depends. Most implementations do what is called [right-to-left evaluation](http://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-from-right-to-left), which means they check every `input[type="text"]` first before determining whether they appear in a `td:nth-child(3)`, rather than limiting their scope first. – BoltClock Sep 16 '14 at 13:03
  • thanks for the explanation! Was anxious about this for a long time! :) – Nikunj Madhogaria Sep 16 '14 at 13:07
  • You don't have to worry. There are some general good practices out there that are worth following, but performance is not something that you have to be concerned with all the time. Build it, then see if it really needs optimizing. – BoltClock Sep 16 '14 at 13:09