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

前端 未结 17 2519
长情又很酷
长情又很酷 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:19

    Perhaps an analogy will help understanding the difference:

    
    
    

    Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.

    It's okay to put multiple students under one Class title, such as Biology. But it's never acceptable to put multiple students under one student ID.

    When giving Rules over the school intercom system, you can give Rules to a Class:

    "Tomorrow, all students are to wear a red shirt to Biology class."

    .Biology {
      color: red;
    }
    

    Or you can give rules to a Specific Student, by calling his unique ID:

    "Jonathan Sampson is to wear a green shirt tomorrow."

    #JonathanSampson {
      color: green;
    }
    

    In this case, Jonathan Sampson is receiving two commands: one as a student in the Biology class, and another as a direct requirement. Because Jonathan was told directly, via the id attribute, to wear a green shirt, he will disregard the earlier request to wear a red shirt.

    The more specific selectors win.

提交回复
热议问题