HTML id 的实际最大长度是多少?

HTML 规范显示

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by 任何数量的 letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

尽管 HTML4的 SGML 声明使用值65536表示 NAMELEN,但它指出“避免固定的限制”

但是浏览器、 CSS 实现和 JavaScript 工具包必须对它们支持的长度有 一些限制。在 HTML/CSS/JS 应用程序中可以安全使用的最小限制是什么?

42767 次浏览

If this is an academic question, it's pretty interesting... but as far as best practices are concerned, you shouldn't need to -- or want to -- stretch these out. If you need to store data about an HTML element, it's better to put it into an attribute on the DOM object.

A practical limit, for me, is however long an ID I can store in my head during the time I'm working with the HTML/CSS.

This limit is usually between 8 and 13 characters, depending on how long I've been working and if the names make sense in the context of the element.

Just tested: 1M characters works on every modern browser: Chrome1, FF3, IE7, Konqueror3, Opera9, Safari3.

I suspect even longer IDs could become hard to remember.

Sometimes I will end up with very long IDs, but I name them consistently to match their exact purpose.

For example...

<div id="page">
<div id="primary-content"></div>
<div id="secondary-content"></div>
<div id="search-form-and-primary-nav-wrapper">
<form id="search-form"></form>
<ul id="primary-nav">
<li id="primary-nav-about-us"></li>
</ul>
</div>
<a id="logo"><img /></a>
</div><!-- /#page -->

As you can see, the selectors are occasionally pretty long. But it's so much easier IMHO than working with something like the YUI grids.css where you end up with IDs like #doc, #bd, #yui-main, etc.