P粉3889454322023-08-18 09:00:04
From HTML 4 Specification:
A common mistake is to use IDs that start with a number.
P粉3641297442023-08-18 00:45:45
For HTML 4, the technical answer is:
HTML 5 is more tolerant and only requires that the id contains at least one character and cannot contain any space characters.
In XHTML, the id attribute is case-sensitive.
From a purely practical perspective, you may want to avoid certain characters. In CSS selectors, periods, colons, and pound signs have special meaning, so you need to use backslashes in CSS or use double backslashes in the selector string passed to jQuery Use the bar to escape these characters. In your stylesheet or code, consider how often you need to escape a character before deciding whether to use periods and colons in ids.
For example, the HTML declaration <div id="first.name"></div>
is valid. You can select this element as #first\.name
in CSS and $('#first\\.name')
in jQuery. But if you forget the backslash, $('#first.name')
, you will get a perfectly valid selector that looks for an id of first
and has a class of Element of name
. This is an easy mistake to overlook. In the long run, you may prefer to choose the id as first-name
(using hyphens instead of periods).
By strictly adhering to naming conventions, you can simplify your development tasks. For example, if you completely restrict yourself to lowercase characters only, and always use hyphens or underscores to separate words (but not both hyphens and underscores, choose one and never use the other), then you have a Easy to remember pattern. You'll never wonder "is it firstName
or FirstName
?" because you always know you should type first_name
. Prefer camelCase nomenclature? Then limit yourself to camelCase only, no hyphens or underscores, and always use uppercase or lowercase as the first character consistently, don't mix them.
A now very uncommon problem is that at least one browser, Netscape 6, incorrectly treats the id attribute value as case-sensitive . This means that if you enter id="firstName"
(lowercase 'f') in HTML, and #FirstName { color: red }
(uppercase 'f') in CSS 'F'), that defective browser will not be able to set the element's color to red. At the time of editing (April 2015), hopefully you don't need to support Netscape 6. Consider this a historical note.