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

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

    ids must be unique where as class can be applied to many things. In CSS, ids look like #elementID and class elements look like .someClass

    In general, use id whenever you want to refer to a specific element and class when you have a number of things that are all alike. For instance, common id elements are things like header, footer, sidebar. Common class elements are things like highlight or external-link.

    It's a good idea to read up on the cascade and understand the precedence assigned to various selectors: http://www.w3.org/TR/CSS2/cascade.html

    The most basic precedence you should understand, however, is that id selectors take precedence over class selectors. If you had this:

    Hello!

    and:

    #intro { color: red }
    .foo { color: blue }
    

    The text would be red because the id selector takes precedence over the class selector.

提交回复
热议问题