treehouse : what would you like to learn today?
Web Design Web Development iOS Development

tag#id vs #id

  • I was wondering why in some cases just the #id is used, but in some other cases tag#id is used. It makes sense to me for classes since you can have multiple classes in a page, but not for ids. It's probably a beginner's question, but that's what I am. :D

    To take it further, sometimes I see things like this:
    body#pagewrap ul#nav li.contact a

    Why not start that from the li or ul if needed?

    These things are still kinda confusing for me, but I'm getting there in my CSS journey.

    Thanks!
  • I think it's mostly used to up the specificity rating of the selector. You get one extra bonus specificity point for declaring the tag as well. The difference between tag#id and #id is pretty negligible, but the difference between .nav-link and div#menu ul li a.nav-link is pretty huge as far as a difference in specificity value. Say you have a style for .nav-link and you have a style for div#menu ul li a. Then in your HTML, you have:

    <div id=\"menu\">
    <ul>
    <li>
    <a class=\"nav-link\"> ...


    The div#menu ul li a styling will trump the .nav-link styling because it has more specificity points. Can get pretty confusing, so it's better to be as specific as you can be.
  • Ok, that makes total sense. It's all about the specificity. I think it was just throwing me off sometimes seeing declarations with a bunch of tags, and looking over their whole document they didn't need to go that far. Maybe they're being specific for future changes, who knows.

    Thanks for the clarification. :thumbsup: