Difference between #id and div#id

后端 未结 9 1788
佛祖请我去吃肉
佛祖请我去吃肉 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:47

    The specificity is different (div#test one is higher) and div#test applies to only a div, not other tags.

    div#test specificity is 0101

    #test specificity is 0100

    Specificity Calculator

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

    As you can see below, div#test is a selector only for divs with the id test. #test will select every element with the id test.

    However, since you should never use an id multiple times, this should not be a problem. div#test will just slow down the matching in the DOM so you shouldn't use it.

    Just to be clear: if you chain elements and ids, you are more specific. This means, these specifications will always override less specific ones.

    div#test{color:green}
    #test{color:red}
    

    The color will be green.


    If you meant div #test, that's for chaining through the DOM tree.

    div#test{ float:right}
    #test{color:green}
    div #test{margin-left:60px}
    <html>
      <head></head>
      <body>
      <div>
        <span>Some stuff here..</span>
      </div>
      <div id="test">
        <span>This is my data</span>
      </div>
      <span id="test">no data</span>
      <div>
        <span id="test">heres data</span>
      </div>
      <div>
        <p>
          <span id="test">heres data aswell</span>
        </p>
      </div>
      </body>
    </html>

    0 讨论(0)
  • 2020-12-22 05:48
    <html>
    <style>
        div#test {
        background: green;
    }
    inspector-stylesheet:1
    #test {
        background: red;
    }
    </style>
    <body><div>
        <span>Some stuff here..</span>
      </div>
      <div id="test">
        <span>This is my data</span>
      </div></body>
    <span id="test">This is my data</span>
    </html>
    

    Basically id's are unique but to show how the element is specific when used with combination div#id if there are two different elements with test for two different elements then the stronger would be the specified element like div#id

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