开发者

unique id value in html

This is a question more out of curiosity rather than being stuck. I know in html id needs to be unique and I can see the error in html validation. Yet the browsers happily apply style sheets to both elements. Is it because they are more relaxed in parsing or what. Does that mean I can use this for styling etc or does it have side effects.

<!DOCTYPE HTML PUBL开发者_运维百科IC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>

<style type="text/css">
  #abc { color: red; }
</style>
</head>
<body>
  <div id="abc">Hello Div 1</div>
  <div id="abc">Hello Div 2</div>
</body>
</html>

Output in browsers.

unique id value in html


If your browser died every time it loaded an HTML page with errors, it'd be dying all the time. And you wouldn't think very much of the browser.

It's important for a browser to be as forgiving as possible and work as best it can with what it has. For this reason, all browsers tend to be very lenient in how they handle markup.

Of course, that doesn't mean you shouldn't write valid HTML.


I would not rely on that behaviour. Having two elements with the same ID is just wrong as you already know.

And yes, the tolerate errors in HTML to some extend and try to compensate. For example missing closing tags. This works more or less good, depending on the error.

Styling several elements should be done with CSS classes.


use "class" for adjusting css.

side effect: you'll feel less comfortable when you want use getElementById and add dynamic functionality. from design perspective doesn't matter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜