HTML - Id Attribute




HTML Id Attribute

The HTML id attribute is a unique identifier. Every id is unique in the entire HTML document, The HTML id is used for Javascript and CSS (Cascading Style Sheet).

This is a very simple description of a very powerful attribute. The ID attribute can performs several actions for Web pages:

Id attribute is also used for linking part, the id value can be used by CSS and JavaScript to perform certain tasks for a unique element with the specified id value.

Example

<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
    background-color: Tomato;
    color: black;
    padding: 35px;
    text-align: center;
} 
</style>
</head>
<body>
<body>
<h1 id="myHeader">Header 1.1</h1>
<h1 id="myHeader">Header 1.2</h1>
</body>
</html>

Result

Header 1.1

Header 1.2

Rules for id Attribute in HTML

There are a few rules you must follow to have a valid document that uses the id attribute anywhere in the document −

The ID must start with a letter (a-z or A-Z)

All subsequent characters can be letters, numbers (0-9), hyphens (-), underscores (_), colons (:), and periods (.).

Spaces are not allowed in values of id attributes. For example, id = "my id"

The values of id attributes are case-sensitive. For example id = "a" and id = "A", both of these are different.

Values of id attributes start with alphabet. For example, id = "myid_1", id = "1_myid"