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

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

    Classes are like categories. Many HTML elements can belong to a class, and an HTML element can have more than one class. Classes are used to apply general styles or styles that can be applied across multiple HTML elements.

    IDs are identifiers. They're unique; no one else is allowed to have that same ID. IDs are used to apply unique styles to an HTML element.

    I use IDs and classes in this fashion:

    
    

    I am a section!

    I am a section!

    I am a section!

    In this example, the header and content sections can be styled via #header and #content. Each section of the content can be applied a common style through #content .section. Just for kicks, I added a "special" class for the middle section. Suppose you wanted a particular section to have a special styling. This can be achieved with the .special class, yet the section still inherits the common styles from #content .section.

    When I do JavaScript or CSS development, I typically use IDs to access/manipulate a very specific HTML element, and I use classes to access/apply styles to a broad range of elements.

提交回复
热议问题