HTML Id Attribute
The id attribute specifies a unique id for an HTML element. The value of the id must be unique within the HTML document.
Using the Id Attribute for CSS and JavaScript
The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.
Example: Styling with an ID
The syntax for an id is: write a hash character (#), followed by an id name. Then, define the CSS properties within curly braces.
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="myHeader">My Header</h1>
</body>
</html>Difference Between Class and ID
A class name can be used by multiple HTML elements, while an id name must only be used by one HTML element within the page.
Using ID for Bookmarks
HTML bookmarks allow users to jump to specific parts of a webpage. Bookmarks are useful if your page is very long. To use a bookmark, you must first create it, and then add a link to it.
Example: Creating a Bookmark Link
This example shows how to create links that jump to a specific chapter on the same page.
<!DOCTYPE html>
<html>
<body>
<p><a href="#C4">Jump to Chapter 4</a></p>
<p><a href="#C10">Jump to Chapter 10</a></p>
<h2>Chapter 1</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 3</h2>
<p>This chapter explains ba bla bla</p>
<h2 id="C4">Chapter 4</h2>
<p>This chapter explains ba bla bla</p>
...
<h2 id="C10">Chapter 10</h2>
<p>This chapter explains ba bla bla</p>
</body>
</html>Test Yourself with an Exercise
Which CSS selector is used to style an element with a specific ID?