Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

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

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 applications for multiple elements sharing the same id?

On my preliminary testing it seems that they apply the id specific CSS rule to all elements with the same id. This behavior seems to be common on IE 8, Chrome, Firefox, Opera.

Is this the sensible choice that browsers make to handle such sloppy HTML or are there exceptions to this behavior? What can be unintended consequences in CSS layout due to sharing of same id amongst multiple elements?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...