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

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

    IDs are unique. Classes aren't. Elements can also have multiple classes. Also classes can be dynamically added and removed to an element.

    Anywhere you can use an ID you could use a class instead. The reverse is not true.

    The convention seems to be to use IDs for page elements that are on every page (like "navbar" or "menu") and classes for everything else but this is only convention and you'll find wide variance in usage.

    One other difference is that for form input elements, the element references a field by ID so you need to use IDs if you're going to use . is an accessibility thing and you really should use it.

    In years gone by IDs were also preferred because they're easily accessible in Javascript (getElementById). With the advent of jQuery and other Javascript frameworks this is pretty much a non-issue now.

提交回复
热议问题