If I have a structure like this:
<div id="main">
<div id="sidebar">
<div id="tag-cloud"/>
</div>
</div>
... what's best practice for css:
#main #sidebar #tag-cloud { ... }
#tag-cloud { ... }
Or if id='main'
was instead class='main'
, would it be worse to scope? I'm just wondering, if you have ids, do you need to scope at all?
The more specific the CSS selector is, the higher is the precedence of the CSS property declarations inside the CSS rule owning the selector. In general terms, the more specifically (uniquely) a CSS selector targets an HTML element, the higher is its specificity.
Simply right click and click Inspect Element. This will bring up the CSS selectors for that element.
Depends. Most of the time, you could say:
#tag-cloud { ... }
is the best (performance-wise, see below). This:
#main #sidebar #tag-cloud { ... }
just does a lot of unnecessary checks that are bound to succeed.
Unless you want to do this:
#sidebar #tag-cloud { ... }
#not-sidebar #tag-cloud { ... }
in which case scoping defines a different look depending on where #tag-cloud
is. Of course there can be only one #tag-cloud
in your page, but your CSS could handle both cases anyway.
CSS checks are done from right to left. This:
#main #sidebar #tag-cloud { ... }
Evaluates to: "The element with ID tag-cloud
that has a parent with ID sidebar
that has a parent with ID main
. If that's how your site looks anyway, that's just a whole lot of useless DOM traversal.
Not to speak of the fact that with over-specific, superfluous scoping the whole CSS must change in a lot of places if you modify your site structure, which somehow defies the purpose.
You already said it yourself: ID's are unique. So, scopes only adds clutter. But if they were intentionally there for pure documentation purposes, I'd replace them by just indenting the rules.
E.g. instead of
#main {
/**/
}
#main #sidebar {
/**/
}
#main #sidebar #tag-cloud {
/**/
}
do
#main {
/**/
}
#sidebar {
/**/
}
#tag-cloud {
/**/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With