When you build websites, you often need to select and style specific parts of your page. HTML provides two important attributes for this: class and id. These help you label elements so you can apply styles using CSS or add behavior with JavaScript. Understanding when and how to use classes and IDs makes your pages easier to manage and more powerful.
class="name"..name { ... }.id="unique-name".#unique-name { ... }.Basic syntax for adding a class and an id to HTML elements:
<!-- Element with a class -->
<p class="highlight">This uses a class.</p>
<!-- Element with an id -->
<h1 id="main-title">This uses an id.</h1>
<!-- Element with both class and id -->
<button id="primary-btn" class="btn primary">Click me</button>
CSS selectors for classes and IDs:
/* Class selector */
.highlight {
color: #0b3d91;
}
/* ID selector */
#main-title {
font-size: 2rem;
}
/* Element with both class and id */
#primary-btn.primary {
padding: 10px 18px;
border-radius: 6px;
}
<!-- Block with a unique ID -->
<div id="main-header" style="background-color: #0b3d91; color: white;
padding: 15px; text-align: center;">
Welcome to My Website
</div>
<!-- Multiple elements share the same class -->
<p class="highlight" style="color: #0b3d91;">This paragraph is highlighted using a class.</p>
<p class="highlight" style="color: #0b3d91;">This is another highlighted paragraph.</p>
Below is how the browser would display the HTML above. The #main-header is styled as a unique banner, and both paragraphs share the same .highlight look.
This paragraph is highlighted using a class.
This is another highlighted paragraph.
class when you want to style or manipulate multiple elements similarly.id for unique elements that appear only once per page (logo, main header, footer, etc.).id on more than one element — this can cause unexpected CSS and JS behavior.#id rules can override .class rules.main-header or primary-button instead of div1 or box.<div> with id="header" and style it with a background color using CSS.highlight; style them with CSS to have a special color and font style.