1

Take this example HTML markup:

<div class="myDivider">
    <p>
        <span></span>
    </p>
    <p>
        <span id="mySpan"></span>
    </p>
</div>

I'd normally just reference the ID using just the ID and nothing more:

#mySpan { ... }

Other than making the code easier to understand, are there any benefits in directing the CSS to the element instead?

.myDivider p #mySpan { ... }

...or with even more specific direction:

div.myDivider > p > span#mySpan { ... }
4

2 に答える 2

2

Quickly reading this article: http://csswizardry.com/2011/09/writing-efficient-css-selectors/

/* Ignore this:

My best guess is that the same with ID's being found slightly faster than classes it's the same with the specifications. Making it clear to your css where to look will make your loading times slightly faster.

*/

After reading it more thoroughly I'm discovering some errors in my guesses. The browser reads the css from the right to the left. It first checks if the right hand element exists in the html and then works it's way up to make sure it is in the right position. So the specifications are mostly just a way to make sure you select the correct element. They do not improve performance, on the contrary.

I suggest you read the article, it's really interesting

于 2013-03-25T12:30:16.403 に答える
1

You could try to optimize for efficiency, but it's not usually worthwhile.

Is all this really necessary?
The short answer is; probably not. (CSS Wizardry, regarding CSS efficiency optimization)

On the other hand, if you have some real-world example wherein a particular element can only appear once-per page, but can appear in different locations within the document, you may wish to style it differently. You can accomplish that by specifying rules even more specific than just the ID.

I can't think of a "real" reason I'd ever need to do this, but here's a silly example -- an easter egg hunt, wherein some egg image appears once per page and needs to scale with particular parent content:

header > #egg {
  width: 64px;
  height: 64px;
}

.navigation > #egg {
  width: 32px
  height: 32px;
}

footer > #egg {
  width: 16px;
  height: 16px;
}

#egg .cleverly-hidden {
  width: 16px;
  height: 16px;
  opacity: 0.5;
  filter: alpha(opacity=50);
}

etc.

It's notable, however, that even though CSS optimization usually yields unnoticeable results, you should still keep things as simple as possible. For your own sanity, and for the fringe chance that your site hits a level of complexity wherein "endless" selector chains in the context of a dynamic document do become noticeable.

于 2013-03-25T14:32:59.247 に答える