HTML id Attribute | Learn HTML
The HTML id attribute defines unique id for an HTML element. This is one of the most used attributes in HTML.
In this tutorial, we will learn about the HTML id attribute and how you can use it in your documents.
Use of HTML id Attribute
The HTML id attribute helps to create a unique identifier for an element. You can not use the same value twice for this attribute in an HTML document.
There are some rules you have to follow to write proper id value for an HTML element. These are:
- The value must begin with an alphabet (a-z or A-Z).
- You can not declare more than one value in a single attribute.
- Whitespace (spaces, tabs, etc) is not allowed to use in id value.
- You can combine numbers (0-9), hyphens (-), underscores (_), colons (:), and periods (.) with the alphabets.
- The HTML id values are case sensitive. Thus <p id=”name”>This is paragraph 1</p> and <p id=”Name”>This is paragraph 2</p> would be considered as a separate id for the same document.
Learn more about other attributes, in our tutorial – HTML Attributes
HTML id Attribute in CSS
You can add CSS styles by using the id attribute. To select an element with an id, use hash (#) followed by the id value of that element.
In this way, you can select a specific element to add CSS.
For example, in the following example, we will create a header with an id attribute. After that, we select that header and style with CSS.
Learn more about CSS, in our tutorial – HTML CSS
Bookmarks with HTML id
HTML bookmarks are useful to jump from one section to another section in a web page.
Bookmarks can be used if your web page is long. Visitors can easily browse the page by using the bookmarks.
To create a bookmark for a specific section, first, you have added an id attribute to that section.
Then create a link by using the id value.
Suppose, we want to jump to a header. Therefore, we have added the id attribute with the value “header1”.
<h2 id="header1">This is our header</h2>
Now we have created a link using that id value (“Jump to Header”).
<a href="#header1">Jump to Header</a>
When someone will click on this link, browser will scroll to that specific header section of that web page.
Learn more about links, in our tutorial – HTML Links
Now all you need to know how we can use this attribute inside an HTML document.
In the above example, you are changing the header text by clicking the “Change Text” button. In this example, we are selecting the header by using the id attribute.
- Each id value has to be unique inside an HMTL document.
- You can select an element using HTML id by adding hash (#) before the id value.
- You can scroll from one section to another section of a web page by creating bookmarks.
- HTML id value must start with an alphabet; you can also use numbers and other characters.
- Use camel case (example, myHeader) while using two words in the id value. Because space is not allowed.
You can learn more about HTML style, in our tutorial – HTML Style