What's the difference between an id and a class?

前端 未结 17 2300
长情又很酷
长情又很酷 2020-11-22 01:55

What\'s the difference between

and
when it comes to CSS? Is it alright to use
<
17条回答
  •  醉话见心
    2020-11-22 02:32

    CSS selector space actually allows for conditional id style:

    h1#my-id {color:red}
    p#my-id {color:blue}
    

    will render as expected. Why would you do this? Sometimes IDs are generated dynamically, etc. A further use has been to render titles differently based on a high-level ID assignment:

    body#list-page #title {font-size:56px}
    body#detail-page #title {font-size:24px}
    

    Personally, I prefer longer classname selectors:

    body#list-page .title-block > h1 {font-size:56px}
    

    as I find using nested IDs to differentiate treatment to be a bit perverse. Just know that as developers in the Sass/SCSS world get their hands on this stuff, nested IDs are becoming the norm.

    Finally, when it comes to selector performance and precedence, ID tends to win out. This is a whole other subject.

提交回复
热议问题