behavior of browsers for css application when multiple elements share same id

后端 未结 3 2100
有刺的猬
有刺的猬 2020-12-21 20:02

I understand that IDs are supposed to be unique in HTML documents. But a lot of HTML pages are sloppy and don\'t follow the rule. My question is: how do browsers handle CSS

相关标签:
3条回答
  • 2020-12-21 20:12

    For an example of unintended consequences, see this question I answered:

    Yet another IE 'Object expected' error with no information

    You have this HTML, once for each tab:

    <div class='tab' id='introduction'>
        <h2 id='introduction'>Introduction</h2>
    </div>
    
    <div class='body' id='introduction' style='display:block'>
    

    The problem is that you're specifying two elements with id='introduction'.

    For various reasons, you should not do that:

    • It's causing validation errors.

      Line 37, Column 27: Duplicate ID introduction.
      Line 36, Column 39: The first occurrence of ID introduction was here.

    • It's breaking your tabs in IE7.
    0 讨论(0)
  • 2020-12-21 20:18

    Since this is something that breaks the rules it's not going to be something you can rely on. All you can do is test in each browser and it's handling might even change with the next version that comes out.

    Handling it as you described seems sensible enough to me. There are probably more complications with how javascript handles this situation rather than css I would imagine.

    I don't think there would be any unintended consequences. There are no problems with using the same class for many elements, why would ids be that different? I can't think of a single case where the basic rules of overriding styles wouldn't work as expected.

    0 讨论(0)
  • 2020-12-21 20:24

    You're right as far as CSS "pretty" display goes, the error recovery is to apply the CSS as if it were a class.

    What can be unintended consequences in CSS layout due to sharing of same id amongst multiple elements?

    Not much to the actual CSS layout, as mentioned above but..

    you might not be able to specifically target (isolate an element) if you need to, and/or the specificity of a selector needed to override a CSS rule with an ID already in it could only be done by adding a unique ID further up the ascendency (or adding an inline <style>)

    also don't think you'll get on very well if you need to use jQuery or something like that, Javascript relies on the ID's for best functionality

    ID's are also Fragment Identifiers - they won't work too well if they're not unique

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