CSS Tutorial: How to Use ID Selectors to Target Elements
📝 Usage
This template demonstrates how to select specific elements using HTML IDs and apply styles to them. Useful for styling elements with specific IDs.
📘 Explanation
The following code applies CSS styles to elements specified by ID attributes. In this example, we select a <div> tag with id="howtocss" and change its text color to blue.
🔹 Partial Code (ID Selector)
/* Style specified by ID */
#howtocss {
color: blue; /* Change text color to blue */
}
💻 Complete Working Code (ID Selector)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS ID Selector Demo</title>
<style>
/* Style specified by ID */
#howtocss {
color: blue; /* Change text color to blue */
}
</style>
</head>
<body>
<div id="howtocss">
<h1>CSS Writing Method</h1>
<p>This is a paragraph.</p>
</div>
</body>
</html>
🧩 Practical Use of ID Selectors
CSS ID selectors are a powerful way to select specific elements using the #idname format. Unlike class selectors, they are suitable for styling unique elements within a page.
🔍 Characteristics of ID Selectors
ID selectors have the following characteristics:
- Only one instance of the same ID name can be used per page
- Higher specificity in CSS (takes precedence over class selectors)
- Can also be used to get elements in JavaScript (
document.getElementById())
💡 Appropriate Use Cases
ID selectors are effective for elements like:
・Main content area (<main id="main-content">)
・Header/Footer (<header id="page-header">)
・Important UI components (<div id="modal-window">)
⚠️ Caution
Overusing ID selectors may cause these issues:
1. Reduced style reusability (cannot apply same style to multiple elements)
2. CSS specificity becomes too high and difficult to manage
3. May require !important when overriding styles later
Best practice is to use class selectors for generic styles and reserve ID selectors for truly unique page elements.