HTML Classes & IDs

class and id attributes are used to identify elements for styling and scripting.

  • class: reusable label you can apply to multiple elements.
  • id: unique identifier for one element in the page (use once).

1) Basic Usage


<p class="intro">This is an intro paragraph.</p>

<div id="main-content">
  ...
</div>


/* CSS */
.intro { font-weight: bold; }
#main-content { padding: 12px; background: #f9f9f9; }

2) Multiple Classes on the Same Element


<span class="badge primary rounded shadow">HTML</span>

HTML CSS JavaScript

3) Unique ID & JavaScript


<button id="clickMe">Click</button>
<p id="status"></p>

<!-- JS -->
<script>
  document.getElementById('clickMe').addEventListener('click', function() {
    document.getElementById('status').textContent = 'Button clicked!';
  });
</script>

When to Use Class vs ID

  • Use class for styles shared among multiple elements (e.g., buttons, cards, alerts).
  • Use id for unique page sections (e.g., header, footer, main banner) or JS hooks.
  • Avoid reusing the same id more than once in a page.

4) Anchor Links to IDs (Page Jumps)


<h2 id="contact">Contact Us</h2>
<a href="#contact">Go to Contact section</a>

Jump to Demo Section

This is the demo section (target of the anchor).

5) CSS Specificity & Good Practices


/* Specificity: ID > Class > Element selector */
h2 { color: #333; }          /* lowest */
.title { color: #0a7; }        /* class */
#hero-title { color: #e91; }   /* highest */

  • Prefer classes for styling; keep IDs for structure and JS hooks.
  • Avoid chaining too many selectors; keep CSS simple and reusable.
  • Use id sparingly to avoid specificity battles.

6) Combining Selectors & Attribute Selectors


/* element with class */
button.primary { background: #0275d8; color: #fff; }

/* element id + class (be cautious: very specific) */
#cta.primary { border: 2px solid #014c8c; }

/* attribute selector */
a[target="_blank"] { text-decoration: underline; }

Tips:

  • You can assign multiple classes to one element: class="btn primary rounded".
  • Only one id is allowed per element, and it should be unique in the document.
  • Use semantic, meaningful names: btn, card, alert, hero, etc.
  • For repeated components, prefer classes over IDs for better reuse.