Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If CSS Selectors are by #id, do you need to scope them?

Tags:

css

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?

like image 260
Lance Avatar asked Sep 27 '10 15:09

Lance


People also ask

What is the precedence between selectors in CSS?

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.

How do I know which CSS selector?

Simply right click and click Inspect Element. This will bring up the CSS selectors for that element.


2 Answers

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.

like image 135
Tomalak Avatar answered Oct 21 '22 16:10

Tomalak


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 {
            /**/
        }
like image 42
BalusC Avatar answered Oct 21 '22 16:10

BalusC