1

This question is about how specific CSS should be specified.
Lets say we have this html page:

<!DOCTYPE>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
    <div>
      <span class="container">
        Hello World!
      </span>
      <span>
        Goodbye World!
      </span>
    </div>
  </body>
</html>

And we want the "Hello World" text to show up red, but not the "Goodbye World!".

In that case we can simply do:

.container {
  color: #FF0000;
}

This will work, because a class is specified for the "Hello World" container. But is this efficient? I mean, the web browser has to look through all HTML available to find the one with the class "container". If we were to the same thing as done above, but being more specific we would get:

html body div span.container {
  color: #FF0000;
}

This way only the span, with the class "container", within a div, within the body, within the html tag will be affected. By being this specific I'd say the web browser is given a lot more directions in what to do. The time it needs to search for the element would, as it seems, be reduced.

Now my question is:
Can the web browser apply the CSS more efficient if it is better specified?

Dennis
  • 323
  • 7
  • 17
  • 1
    If you want to be more specific, use its `id` as it's unique to the element. – kums Nov 02 '14 at 09:11
  • you would use a more specified CSS if you would like to overwrite the previous CSS (here the red text). Again you could overwrite that more specified CSS with `!important`. If a style should be a finite style it makes sense to specify it more specific, but in other cases it makes no sense I think. – pbaldauf Nov 02 '14 at 09:12
  • 7
    I've read that browsers parse css selectors from right to left in which case the simple `.container` would be quicker as it can stop looking for the other conditions. However, I personally think that matching css selectors to DOM elements has been optimized in the browser so much that in most cases it doesn't really matter – ckuijjer Nov 02 '14 at 09:13
  • @ckuijjer One of the greatest comments, ever. – Hashem Qolami Nov 02 '14 at 11:17

0 Answers0