Difference between #id and div#id

后端 未结 9 1787
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 04:52

I am new to css. Can someone help me in differentiating \"#test\" and \"div#test\"?

相关标签:
9条回答
  • 2020-12-22 05:33

    You really ought not to qualify an ID with a tagname per the MDN, as follows:

    Don’t qualify ID rules with tag names or classes

    If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs are unique, adding a tag name would slow down the matching process needlessly

    0 讨论(0)
  • 2020-12-22 05:33

    When you use div#id it will only apply to #id that is attached to a div. Specificity of div#id is more than that of #div.

    0 讨论(0)
  • 2020-12-22 05:34

    The #id is Selects the element with id="firstname". It is one kind of CSS Selectors.

    Check all CSS Selectors at https://www.w3schools.com/cssref/css_selectors.asp

    There is a minor difference.

    When you use div#id it will only apply to #id that are attached to a div. Otherwise the rule is ignored.

    Hope it helps. Thanks

    0 讨论(0)
  • 2020-12-22 05:35

    #test will take the element with the id test while div#test will only take the div with an id named test. This doesn't make a great difference since ids have to be unique.

    This kind of info is pretty easy to find, you may want to take a look at W3schools documentation

    0 讨论(0)
  • 2020-12-22 05:35

    #id & div#id differs only when applying styles to that element.

    Browser calculates the most relevant element by calculating specificity.

    specificity calculate rules are in the follwing link https://www.w3.org/TR/CSS22/cascade.html#specificity

    #id will be 0100 and div#id will be 0103

    So what does the number means if you write

    div#id {
      background: green;
    }
    
    #id {
      background: red;
    }
    

    the color of box will be green

    reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

    0 讨论(0)
  • 2020-12-22 05:38

    The main difference is the specifity weight changes.

    Doing #id is less specific than div#id

    This means that your div#id rules are used because it has a higher specifity value

    div#id {background: #000} 
    #id {background: #fff} 
    

    The background of the div with that id will be black, even if another rule is selected afterwards

    0 讨论(0)
提交回复
热议问题