What are valid values for the id attribute in HTML

2020-01-22 10:25发布

When creating the id attributes for HTML elements, what rules are there for the value?

标签: html id
23条回答
我命由我不由天
2楼-- · 2020-01-22 11:21

No spaces, must begin with at least a char from a to z and 0 to 9.

查看更多
我只想做你的唯一
3楼-- · 2020-01-22 11:24

Also, never forget that an ID is unique. Once used, the ID value may not appear again anywhere in the document.

You may have many ID's, but all must have a unique value.

On the other hand, there is the class-element. Just like ID, it can appear many times, but the value may be used over and over again.

查看更多
欢心
4楼-- · 2020-01-22 11:25

From the HTML 4 specification:

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

A common mistake is to use an ID that starts with a digit.

查看更多
成全新的幸福
5楼-- · 2020-01-22 11:25

HTML5

Keeping in mind that ID must be unique, ie. there must not be multiple elements in a document that have the same id value.

The rules about ID content in HTML5 are (apart from being unique):

This attribute's value must not contain white spaces. [...] 
Though this restriction has been lifted in HTML 5, 
an ID should start with a letter for compatibility.

This is the W3 spec about ID (från MDN):

Any string, with the following restrictions:
must be at least one character long
must not contain any space characters
Previous versions of HTML placed greater restrictions on the content of ID values 
(for example, they did not permit ID values to begin with a number).

More info:

  • W3 - global attributes (id)
  • MDN atribute (id)
查看更多
Lonely孤独者°
6楼-- · 2020-01-22 11:26

To reference an id with a period in it you need to use a backslash. Not sure if its the same for hyphens or underscores. For example: HTML

<div id="maintenance.instrumentNumber">############0218</div>

CSS

#maintenance\.instrumentNumber{word-wrap:break-word;}
查看更多
登录 后发表回答