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

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

    Using the same ID for multiple items causes your HTML to be invalid.

    The simple answer is just that. If you're using an ID (a unique identifier) multiple times you're invalidating your HTML.

    Just as chewing gum can be used to stick a painting to a wall, the same ID can be used multiple times because HTML doesn't handle errors in a draconian fashion. It still doesn't make it correct or even a good use of the attribute.

    Classes are designed so that you can relate multiple elements on a page. This is what it's designed for.

    0 讨论(0)
  • 2021-01-29 11:53

    You have heard correctly. The behavior you are seeing is the result of browsers being coded to be extremely accommodating in the face of gross violations of the HTML standard.

    The idea behind the fact that they have been coded to work even when presented with "bad" data is that, to less technically proficient users, it's the browser's fault if something does not work. Browsers were forced to work with tag soup, and this is the logical extension.

    0 讨论(0)
  • 2021-01-29 11:59

    In CSS terms, ID's are faster to find than classes.

    You should use classes for things that are to be re-used.

    EG:

    @CSS
    
    .displayNone
    {
        display:none;
    }
    
    0 讨论(0)
  • 2021-01-29 12:07

    An ID is used to reference certain elements when using JQuery / Javascript etc, so technically if you wish to utilise these features then IDs on your page should be unique.

    If you are only bothered about styling then it really isn't a huge issue, although it isn't valid practice.

    0 讨论(0)
  • 2021-01-29 12:09

    If you care for XHTML/HTML validation, then you should use unique IDs.

    See this:

    Class vs. ID

    And

    Why must the ID attribute be unique on each page?

    Hope it helps.

    0 讨论(0)
  • 2021-01-29 12:11

    I have heard that ID is unique and can only be used once in a page

    That is an HTML rule and has nothing to do with CSS.

    but its working fine when used over multiple times on a page.

    Browsers perform error recovery. Don't depend on it as not all browsers will recover from all errors in the same way. Write valid markup.

    Please let me know the purpose of ID and hows its exactly different from classes?

    In HTML terms — an id is unique per document and can be a link target. A class can be reused.

    In CSS terms — An id selector has a higher specificity than a class selector.

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