DevAcademy
LearnHTMLClasses & IDs
IntermediateHTML

Classes & IDs

Learn how to target elements for CSS styling and JavaScript using the class and id attributes.

Reading Time

12 min

Lesson

Lesson 19 of 27

Why We Need Selectors

To style or manipulate specific elements with CSS or JavaScript, you first need a way to target them. The class and id attributes are the two most common hooks for this.

class and id

<div id="main-banner" class="banner highlight">
  Welcome to DevAcademy!
</div>
Output

class vs id

classid
UniquenessCan be reused on many elementsMust be unique on the page
Multiple valuesYes, space-separatedNo, only one value
CSS selector.classname#idname
Typical useReusable stylingUnique anchors, JS hooks, ARIA references

Selecting in CSS

<style>
  .highlight {
    background: yellow;
  }
  #main-banner {
    font-size: 1.5rem;
  }
</style>
Output

Multiple Classes

An element can have several classes separated by spaces. This lets you compose small, reusable style rules instead of writing one large class per component.

Multiple Classes Example

<button class="btn btn-primary btn-large">Sign Up</button>
Output

Using id as an Anchor

Besides styling, id is commonly used as a target for same-page links (<a href="#section">) and as a hook for JavaScript’s document.getElementById().

Duplicate IDs Are Invalid

Using the same id value on more than one element in a page is invalid HTML. It can cause CSS to apply inconsistently and break JavaScript methods that expect a single match.

Best Practice

Default to class for styling since it’s reusable across many elements. Use id sparingly — only when you need a guaranteed single, unique reference.

Interview Questions

Quick Quiz

1. Which attribute must be unique across the entire page?

2. How do you write a CSS selector that targets a class named "card"?

3. Can a single element have more than one class?