Use css selector or more directly id?
this more a conceptual question. Recently i found myself to be more confident with this kind of html (example)
<div id="mainCont">
<div id="mainContFirst">Text <span id="mainContFirstSpan">option</span></div>
<div id="mainContSecond">Other Text</div>
</div>
Having all important tag marked with an ID you can easly write down css:
#mainContFirst {} etc
is this a bad pratice? Should I use just css selector? Is this faster then use selector?
Thanks
Grouping (edit)
开发者_Go百科Ok now What about elements that should have the same style?
let's say for example in every divs the second <span>
should have font-size:10px;
it's better this:
<div>
text text <span></span> <span id="firstDivSpan"></span>
</div>
<div>
text text <span></span> <span id="secondDivSpan"></span>
</div>
and then the css:
#firstDivSpan, #secondDivSpan {...}
Or like this?
<div>
text text <span></span> <span id="firstDivSpan" class="commonStyle"></span>
</div>
<div>
text text <span></span> <span id="secondDivSpan" class="commonStyle"></span>
</div>
.commonStyle{...}
What's better?
ID selectors are the fastest. That is not bad practice at all; you're simply operating under the assumption that there will only be one element with that ID on your pages.
That said you shouldn't abuse IDs for lame reasons like rendering performance. Use IDs to mark truly unique elements, not to mark everything so you can forget about stuff like descendant combinators, classes, groups etc. Those other selectors are what make CSS so powerful, not just the ID selectors.
Re question edit: there isn't any better one in this case. Performance issues aside (because they don't matter at all) it largely depends on the meaning of the selectors.
If your styles apply to any element with the .commonStyle
class then use the class selector. If you only want to target those two specific span
s regardless of the class then the ID selectors are more appropriate.
It is better to use the ID like in your example. It is easier for the browser to fetch a particular ID element rather than have to find all parents, then descendants...
As someone expanded on my answer in a separate thread, article regarding this: http://www.css-101.org/descendant-selector/go_fetch_yourself.php
ID, class, element name - they are all CSS selectors.
精彩评论