ID vs CLASS in CSS. Please explain in detail with example

后端 未结 8 1693
不思量自难忘°
不思量自难忘° 2021-01-29 11:46

I have heard that ID is unique and can only be used once in a page, but its working fine when used over multiple times on a page. Please let me know the purpose of ID and hows i

8条回答
  •  故里飘歌
    2021-01-29 12:17

    If I can use an analogy of cars:

    ID is like a Registration Plate

    • supposed to be unique - allows you to uniquely identify and style a single element

    Class is like a Vehicle Model

    • allows you to deal with a set of related elements in one go.

    Continuing the anaology:

    It's fine to duplicate registration plates in so far as the cars still work - but the police would get quite annoyed! How would you identify a particular driver as having been speeding?

    The same applies with HTML elements - reusing the same ID just stops you identifying a single element when you need to.

提交回复
热议问题