Home > Article > Web Front-end > Can HTML IDs Start with Numbers, and How Does This Affect CSS Styling?
Can Elements Have ID Values That Start with Numbers?
Yes, it is possible to create HTML elements with ID values that start with numbers or consist entirely of numbers, as in <div>.
Technical Validity and Styling Considerations
While such ID values are technically valid according to the HTML5 specification, they pose challenges when using CSS selectors to target them. Specifically, ID values that begin with digits cannot be used literally in CSS selectors and require escaping using backslashes, e.g., #12 must be written as #3132.
Recommendation for CSS Styling
If you intend to use CSS to style elements with numeric IDs, it is advisable to start the IDs with letters to avoid the need for escaping. This simplifies the process and ensures compatibility across browsers.
Example
Consider the following HTML code:
<div>
Using JavaScript, you can set the border and font style of the div element as follows:
document.getElementById("12").style.border = "2px solid black"; if (document.querySelector) { document.querySelector("#\31\32").style.fontStyle = "italic"; }
The CSS code to set the background color of the div element would be:
# { background: #0bf; }
Note that the CSS selector requires the ID value to be escaped using backslashes.
The above is the detailed content of Can HTML IDs Start with Numbers, and How Does This Affect CSS Styling?. For more information, please follow other related articles on the PHP Chinese website!