In HTML, an ID is a unique identifier assigned to a single HTML element. Unlike classes, which can be applied to multiple elements, each ID should be unique within a page, meaning it can be assigned to only one element. IDs are useful for styling unique elements and for targeting elements in JavaScript.
IDs are useful when you need to uniquely style or select a specific element on a page. For example, you might use an ID to style a unique header or to create a section anchor link. IDs are also commonly used in JavaScript to manipulate specific elements.
Here’s a basic example of using an ID to style a unique paragraph element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome To My Id Page</title>
<style>
#main-header {
font-size: 1.5em;
color: #e74c3c;
border-bottom: 2px solid #3498db;
padding-bottom: 5px;
}
</style>
</head>
<body>
<p id="unique-element">This paragraph has a unique style.</p>
</body>
</html>
This paragraph has a unique style.
You can use an ID to style a unique header. Here’s an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome To My Id Page</title>
<style>
#main-header {
font-size: 1.5em;
color: #e74c3c;
border-bottom: 2px solid #000000;
padding-bottom: 5px;
}
</style>
</head>
<body>
<h2 id="main-header">Main Section Header</h2>
</body>
</html>
Main Section Header
IDs are also commonly used to select elements in JavaScript. Here’s an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unique ID Styling</title>
<style>
#highlighted-section {
background-color: #f9c74f;
color: #333;
padding: 10px;
border-radius: 5px;
font-family: Arial, sans-serif;
font-size: 1.2em;
}
</style>
</head>
<body>
<h1>Welcome to My Unique ID Page</h1>
<div id="highlighted-section">
This is a specially styled section with a unique ID.
</div>
<p>Other content on the page is styled differently or not at all.</p>
</body>
</html>
Welcome to My Unique ID Page
This is a specially styled section with a unique ID.
Other content on the page is styled differently or not at all.
IDs in HTML provide a way to uniquely identify elements for styling and JavaScript manipulation. While IDs are powerful, remember to use them sparingly and only when you need a unique identifier. For reusable styling, classes are often a better choice.