HTML ID | Unique Identifier for Elements

HTML ID is an attribute used to uniquely identify an element in an HTML document. Unlike classes, IDs are specific to a single element and are commonly used for styling, navigation, and JavaScript manipulation.

Using IDs in HTML:

The `id` attribute is defined within an HTML tag and must have a unique value within the document.

Basic Example of HTML ID

<!DOCTYPE html>
<html>
<head>
<title>HTML ID Example</title>
<style>
    #unique-element {
        color: white;
        background-color: #ff6347;
        padding: 10px;
        border-radius: 5px;
    }
</style>
</head>
<body>
<p id="unique-element">This paragraph is styled using the 'unique-element' ID.</p>
<p>This paragraph does not have an ID applied.</p>
</body>
</html>

Using IDs for Navigation:

IDs can be used as anchors for navigation links:

Code Example


<!DOCTYPE html>
<html>
<head>
    <title>HTML ID Navigation Example</title>
    <style>
        #section1 {
            color: #333;
            margin-top: 50px;
        }
        #section2 {
            color: #333;
            margin-top: 50px;
        }
    </style>
</head>
<body>
    <a href="#section1">Go to Section 1</a> | 
    <a href="#section2">Go to Section 2</a>

    <h2 id="section1">Section 1</h2>
    <p>This is the content of Section 1.</p>

    <h2 id="section2">Section 2</h2>
    <p>This is the content of Section 2.</p>
</body>
</html>

Output

Go to Section 1 | Go to Section 2

Section 1

This is the content of Section 1.

Section 2

This is the content of Section 2.

Benefits of Using HTML IDs:

Best Practices:

HTML IDs are a powerful tool for targeting specific elements in your webpage. Use them wisely to enhance your web development projects while maintaining clean and maintainable code.