In this tutorial, you will learn the HTML id Attribute
The HTML id attribute is used to uniquely identify a specific element on a web page. This can be useful for applying CSS styles or JavaScript functionality to a specific element.
- To create an id, use the “id” attribute in the opening tag of an HTML element. For example:
<div id="myid">
- In your CSS file, use a “#” followed by the id name to define the styles for that id. For example:
#myid {
color: blue;
}
- To apply the id to an element, simply use the same id attribute on the desired element. For example:
<div id="myid">This is a div with the id "myid"</div>
- Unlike class attributes, id attributes must be unique on a page, meaning that no two elements can have the same id.
- If you want to apply styles or JavaScript functionality to multiple elements, you can use class attributes instead.
Here is an example of a complete HTML and CSS that uses an id attribute:
<!DOCTYPE html>
<html>
<head>
<style>
#header {
background-color: blue;
color: white;
}
</style>
</head>
<body>
<div id="header">This is the header</div>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
In this example, the id “header” is used to apply a blue background color and white text color to the first div element.
In summary, the ID attribute is used to uniquely identify an element on a web page and allows you to apply styles or JavaScript functionality to a specific element. However, remember that id attributes must be unique on a page, if you want to apply styles or functionality to multiple elements, you can use class attributes instead.