← Learning Hub
Beginner

Selectors

Selectors choose which elements a rule applies to. The three you will use most are:

  • Element selector: p styles every paragraph.
  • Class selector: .price styles every element with class="price". Many elements can share a class.
  • ID selector: #logo styles the one element with id="logo". An ID must be unique on the page.

Choosing the right selector is like addressing a letter: "to everyone in the building" (element selector), "to everyone in the sales team" (class) or "to Riya only" (ID). Classes are the workhorse of CSS because you can reuse them anywhere - give every price class="price" and style them all at once.

You can also combine selectors: .card h2 styles h2 headings only inside cards, and h1, h2 styles both. These combinations let you target exactly the elements you want without adding classes everywhere.

Example
<!DOCTYPE html>
<html>
  <head>
    <style>
      p { color: #333; }
      .price { color: green; font-weight: bold; }
      .old { text-decoration: line-through; color: #999; }
      #title { color: #e11d48; }
      li:hover { background: #fef3c7; }
    </style>
  </head>
  <body>
    <h2 id="title">Festival Offer</h2>
    <p>Now only <span class="price">₹499</span> <span class="old">₹799</span></p>
    <ul>
      <li>Hover over me</li>
      <li>And over me</li>
    </ul>
  </body>
</html>
▶ Try it yourself
:hover is a pseudo-class: it applies only while the mouse is over the element. Prefer classes for most styling; keep IDs for special cases.
Key points
  • Element (p), class (.price) and ID (#logo) selectors.
  • Classes are reusable; IDs are unique - prefer classes.
  • Pseudo-classes like :hover style elements in a certain state.

📝 Test yourself

1. Which selector matches class="card"?
2. How many elements may share one ID?
3. Fill in the pseudo-class for mouse-over:
a: { color: red; }