OnlineCBT Logo OnlineCBT
CSS Tutorial
CSS · LESSON 4

Basic Selectors: Element, Class, and ID

By Ratan Updated: 15 Oct 2026

Target HTML elements using tag names, class names (.class), and unique IDs (#id).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Select by element type, reusable class or unique ID

A type selector such as p matches paragraph elements. A class selector such as .note matches a token in an element's class attribute. An ID selector such as #summary targets an element with that exact ID; IDs should be unique within a document.

p { line-height: 1.6; }
.note { padding: 1rem; background: #eff6ff; }
.note.urgent { border-left: 4px solid #b91c1c; }
#summary { max-width: 40rem; }

Read the instructions.

Submit before the deadline.

Both paragraphs receive the type rule and note styling. Only the second matches .note.urgent because it has both classes on the same element. A space changes the meaning: .note .urgent selects an urgent descendant inside a note, not an element with both classes.

Prefer classes for components

Classes are reusable and keep component specificity manageable. IDs remain useful for fragment links, accessible label relationships and scripting targets. Repeating an ID on every card creates invalid document identity and can break those relationships; use a class for repeated styling.

Case and token matching

In ordinary HTML, write class and ID names consistently, including their case. class="note urgent" contains two class tokens. A selector .note matches the note token; it does not require the entire attribute to equal "note".

Inspect before increasing specificity

If a color does not apply, first check that the element actually has the expected class and the stylesheet is loaded. An unmatched selector cannot be fixed by adding !important. In developer tools, inspect the matched rules and the source of the winning property.

Exercises

  1. Create three buttons sharing .button and give one an additional .button-primary class.
  2. Explain the difference between p.note and p .note: the first is a paragraph with the class, the second is a descendant with the class inside a paragraph.
  3. Replace repeated card IDs with a shared card class.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat