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

后端 未结 8 1667
不思量自难忘°
不思量自难忘° 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:11

    Confusion abound here. Turns out, everybody is kinda right. Here are the facts:

     1. CSS doesn't care much which you use, as far as actually applying
        styling. ID's are technically faster for a browser rendering engine,
        but other than the most extreme of circumstances you'll probably
        never notice a speed difference
     2. . JavaScript cares very much about ID's. It can be noticeably faster
        for JavaScript to find an element by an ID. And this is where the
        "uniqueness" is very important. JavaScript will only find the
        "first" element with that ID, so if you have multiple on the page,
        confusion may ensue.
     3. ID's have an infinitely higher specificity value than classes. If
        there is an element with an ID and a class and they both apply
        styles, the styles applied by the ID will take precedence over the
        styles applied by the class. This can be useful, this can be a
        hindrance.
    

    here is simplest example

    #id    { color: red; }
    .class { color: green; }
    

    It's just an attribute and it's a seemingly arbitrary difference in syntax depending on which one you use. The results are predictable:

    <div id="id">Would be red</div>
    <span id="id">Would be red</div>
    
    <div class="class">Would be green</div>
    <span class="class">Would be green</div>  
    

    REFERENCE

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题