CSS Tutorial – Lesson 3

CSS Selectors – All Types Explained with Examples And Live Preview (2026-27)

CSS selectors are patterns used to select and target the HTML elements you want to style. Every CSS rule starts with a selector — without it, CSS has nothing to apply to. There are many types of CSS selectors, from the simple element selector (targets all <h1> tags) to powerful pseudo-class selectors (:hover, :focus) and attribute selectors (input[type='text']). Knowing which selector to use — and when — is one of the most important skills in CSS. In this beginner-friendly guide you will learn all 10 CSS selector types with live code examples, a complete reference table, specificity rules, interactive playground, and a quiz to test your knowledge.



✅ What is a CSS Selector?

A CSS selector is the first part of a CSS rule — it defines which HTML element(s) the style should be applied to. It is written before the opening curly brace {.

✅ Without a selector, CSS cannot know where to apply the styles.

✅ Selectors can target all elements of a type, elements with a specific class or ID, elements in a specific state, or even virtual parts of elements.

h1 ← SELECTOR: targets all h1 elements { color: #1E3A5F; font-size: 28px; } .card ← CLASS SELECTOR: targets all class="card" elements { background: #fff; } #header ← ID SELECTOR: targets element with id="header" { height: 80px; }

✅ All CSS Selector Types – Overview

el
Element Selector
Targets HTML tag
p { color: red; }
.cls
Class Selector
Targets class attribute
.btn { padding: 10px; }
#id
ID Selector
Targets unique ID
#nav { display: flex; }
*
Universal Selector
Targets every element
* { margin: 0; }
A,B
Group Selector
Targets A and B
h1, h2 { color: navy; }
A B
Descendant Selector
B inside A
nav a { color: blue; }
A>B
Child Selector
Direct children only
ul > li { list-style: none; }
:hover
Pseudo-class
Element states
a:hover { color: red; }
::
Pseudo-element
Virtual element parts
p::first-line { }

✅ 1. Element Selector

The element selector targets all HTML elements of a specific tag type. It is the simplest selector and is written as just the tag name.

Syntax:-

/* Targets ALL p elements on the page */
p {
  color: #333;
  font-size: 16px;
  line-height: 1.8;
}

/* Targets ALL h1 elements */
h1 {
  color: #1E3A5F;
  font-size: 32px;
  font-weight: bold;
}

/* Targets ALL anchor links */
a {
  color: #0EA5E9;
  text-decoration: none;
}
💡 Use case: Element selectors are ideal for setting base/default styles — reset margins, set a global font, define heading sizes. For component-specific styles, use class selectors instead.
⚠️ Be careful with broad element selectors. p { font-size: 14px; } changes ALL paragraphs site-wide. Use class selectors when you only want to target specific paragraphs.

✅ 2. Class Selector (.classname)

The class selector targets all elements with a specific class attribute. It starts with a dot (.) followed by the class name. Classes are the most commonly used selector in real CSS projects.

Syntax:-

/* CSS — class selector with . prefix */
.highlight {
  background: yellow;
  padding: 2px 6px;
}

.btn-primary {
  background: #0EA5E9;
  color: #fff;
  padding: 10px 24px;
  border-radius: 6px;
  border: none;
}

HTML using class:-

<p>This word is <span class="highlight">highlighted</span>.</p>
<button class="btn-primary">Click Me</button>
<a href="#" class="btn-primary">I am also a button</a>
ℹ️ Key rules for class selectors:
✅ Class names are case-sensitive.Btn.btn
✅ One element can have multiple classesclass="btn btn-primary large"
✅ Same class can be applied to multiple elements — reusable
✅ Class names should be descriptive and lowercase.nav-link not .NL

✅ 3. ID Selector (#idname)

The ID selector targets the one element with a specific id attribute. It starts with a hash (#) followed by the ID name. IDs must be unique — only one element per page should have a given ID.

Syntax:-

/* CSS — ID selector with # prefix */
#main-header {
  background: #1E3A5F;
  color: #fff;
  height: 80px;
  padding: 0 24px;
  display: flex;
  align-items: center;
}

#hero-section {
  background: linear-gradient(135deg, #F0F9FF, #E0F2FE);
  padding: 80px 40px;
  text-align: center;
}

HTML using ID:-

<header id="main-header">
  <h1>LearnToSAP.com</h1>
</header>

<section id="hero-section">
  <h2>Learn CSS Step by Step</h2>
</section>
⚠️ ID rules: Each ID value must appear only once per page. Using the same ID on multiple elements is invalid HTML and causes JavaScript errors. For repeated styles, always use classes. Use IDs only for page landmarks (header, main, footer) or JavaScript hooks.

✅ 4. Universal Selector (*)

The universal selector (*) targets every element on the page. It is most commonly used in CSS resets to remove default browser styles.

Example:-

/* CSS reset — remove all default margins and padding */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Reset combined with child selector */
.card * {
  font-family: Arial, sans-serif;
  color: #333;
}
ℹ️ box-sizing: border-box — The most important universal selector use case. This single rule changes how width/height is calculated across all elements, making layouts far more predictable. It's included in virtually every modern CSS project.

✅ 5. Group Selector (A, B)

The group selector applies the same CSS rule to multiple selectors at once by separating them with commas. This is the DRY (Don't Repeat Yourself) approach to CSS.

Without grouping (repetitive):-

h1 { color: #1E3A5F; font-family: Arial, sans-serif; }
h2 { color: #1E3A5F; font-family: Arial, sans-serif; }
h3 { color: #1E3A5F; font-family: Arial, sans-serif; }

With grouping (clean and DRY):-

/* One rule for three selectors */
h1, h2, h3 {
  color: #1E3A5F;
  font-family: Arial, sans-serif;
}

/* Mix elements and classes */
input, textarea, select {
  border: 1px solid #ddd;
  padding: 8px 12px;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}

✅ 6. Descendant & Child Selectors

These selectors target elements based on their position inside another element.

SelectorSymbolWhat it selectsExample
DescendantA B (space)All B inside A (any depth)nav a { }
ChildA > BDirect children B of A onlyul > li { }
Adjacent SiblingA + BFirst B immediately after Ah1 + p { }
General SiblingA ~ BAll B that follow Ah1 ~ p { }

Examples:-

/* Descendant: all links inside nav */
nav a {
  color: #0EA5E9;
  text-decoration: none;
}

/* Child: only direct li inside ul */
ul > li {
  list-style: none;
  padding: 8px 0;
}

/* Adjacent sibling: p right after h2 */
h2 + p {
  font-size: 16px;
  color: #666;
  margin-top: 0;
}

✅ 7. Pseudo-class Selectors (:hover :focus :nth-child)

A pseudo-class targets an element in a specific state — like when a user hovers over it, clicks it, or when it is the first element in a list. Written with a single colon (:).

Most Common Pseudo-classes:-

/* Hover state — mouse over element */
a:hover {
  color: #0284C7;
  text-decoration: underline;
}

button:hover {
  background: #0284C7;
  transform: translateY(-1px);
}

/* Focus state — form element is active */
input:focus {
  border-color: #0EA5E9;
  outline: none;
  box-shadow: 0 0 0 3px rgba(14,165,233,0.2);
}

/* First and last child */
li:first-child { font-weight: bold; }
li:last-child  { border-bottom: none; }

/* Nth child — target specific positions */
tr:nth-child(even) { background: #F0F9FF; } /* alternating rows */
tr:nth-child(odd)  { background: #fff; }

/* Not selector */
p:not(.special) { color: #444; } /* all p except .special */
Pseudo-classWhat it targets
:hoverElement when mouse is over it
:focusElement when it has keyboard/click focus
:activeElement while being clicked
:visitedLink that has been visited
:first-childFirst child of its parent
:last-childLast child of its parent
:nth-child(n)The nth child (even, odd, or number)
:not(selector)Every element that does NOT match selector
:checkedChecked checkbox or radio button
:disabledDisabled form element
:placeholder-shownInput with visible placeholder text

✅ 8. Pseudo-element Selectors (::before ::after)

A pseudo-element targets a virtual part of an element — content that doesn't physically exist in the HTML but can be styled with CSS. Written with a double colon (::).

Most Used Pseudo-elements:-

/* ::before — insert virtual content before the element */
.quote::before {
  content: '"';
  color: #0EA5E9;
  font-size: 40px;
  font-weight: bold;
  line-height: 0;
  vertical-align: -15px;
  margin-right: 4px;
}

/* ::after — insert virtual content after the element */
.required-field::after {
  content: ' *';
  color: red;
  font-weight: bold;
}

/* ::first-line — style the first line of text only */
p::first-line {
  font-weight: bold;
  color: #1E3A5F;
}

/* ::first-letter — style the first letter only */
p::first-letter {
  font-size: 3em;
  float: left;
  color: #0EA5E9;
  margin-right: 4px;
  line-height: 0.8;
}

/* ::placeholder — style placeholder text in inputs */
input::placeholder {
  color: #aaa;
  font-style: italic;
}
ℹ️ ::before and ::after are extremely powerful. They are used for decorative elements (icons, shapes, underlines), tooltips, custom list bullets, clearfix hacks, and overlay effects — all without adding extra HTML elements.

✅ 9. Attribute Selectors ([attr=value])

Attribute selectors target elements based on their HTML attributes and attribute values. They use square brackets [ ].

Examples:-

/* Exact match — input where type equals "text" */
input[type="text"] {
  border: 1px solid #ddd;
  padding: 8px;
  border-radius: 4px;
}

/* Has attribute — images that have an alt attribute */
img[alt] {
  border: 2px solid #d4edda; /* green border = accessible */
}

/* Starts with — links to external sites (https) */
a[href^="https"] {
  color: #2e7d32; /* green for secure links */
}

/* Ends with — links to PDF files */
a[href$=".pdf"] {
  color: #c0392b;
}
a[href$=".pdf"]::after {
  content: " 📄";
}

/* Contains — any element where class contains "btn" */
[class*="btn"] {
  cursor: pointer;
  border-radius: 6px;
}

/* Language attribute */
[lang="en"] {
  font-family: Arial, sans-serif;
}
SelectorMatches when...Example
[attr]Element has the attribute (any value)img[alt]
[attr="val"]Attribute equals exactly "val"input[type="text"]
[attr^="val"]Attribute value starts with "val"a[href^="https"]
[attr$="val"]Attribute value ends with "val"a[href$=".pdf"]
[attr*="val"]Attribute value contains "val"[class*="btn"]
[attr~="val"]Attribute is a space-separated list containing "val"[class~="active"]

✅ Class vs ID – Key Differences

FeatureClass (.classname)ID (#idname)
Syntax in CSS.btn#header
Syntax in HTMLclass="btn"id="header"
Reusability✅ Can be used on many elements❌ Must be unique per page
Multiple per element✅ Yes — class="a b c"❌ Only one ID per element
Specificity0,1,0 (medium)1,0,0 (high)
JavaScript targetinggetElementsByClassName()getElementById()
Best forReusable components, utility stylesPage landmarks, JS hooks
💡 Rule of thumb: Default to using classes for CSS styling. Use IDs only when something is truly unique on the page (like #main-header) or as a JavaScript target. Overusing IDs in CSS leads to specificity wars that are hard to override.

✅ Selector Specificity

When multiple CSS rules target the same element, specificity determines which rule wins. Higher specificity = rule takes priority.

Selector TypeSpecificity ScoreExamplePoints
!importantOverrides everythingcolor: red !important
Inline style1,0,0,0style="color:red"1000
ID selector0,1,0,0#nav100
Class / attribute / pseudo-class0,0,1,0.btn, [type], :hover10
Element / pseudo-element0,0,0,1h1, p, ::before1
Universal selector0,0,0,0*0

Specificity calculation examples:-

p              /* 0,0,0,1 = score:   1 — element */
.text          /* 0,0,1,0 = score:  10 — class   */
#main          /* 0,1,0,0 = score: 100 — ID      */
p.text         /* 0,0,1,1 = score:  11 — element + class */
#main p.text   /* 0,1,1,1 = score: 111 — ID + element + class */
⚠️ When specificity ties: The rule that appears later in the CSS file wins — this is the cascade. Write more general rules first, more specific rules last.

✅ Complete CSS Selector Reference Table

SelectorTypeWhat it selectsExample
*UniversalAll elements* { box-sizing: border-box; }
elementElementAll elements of tag typep { color: #333; }
.classClassAll with class attribute.btn { padding: 10px; }
#idIDOne element with unique ID#header { height: 80px; }
A, BGroupBoth A and Bh1, h2 { font-family: Arial; }
A BDescendantB inside A (any depth)nav a { color: blue; }
A > BChildDirect children B of Aul > li { list-style: none; }
A + BAdjacent siblingFirst B right after Ah1 + p { margin-top: 0; }
A ~ BGeneral siblingAll B after Ah1 ~ p { color: #555; }
:hoverPseudo-classOn mouse overa:hover { color: red; }
:focusPseudo-classOn keyboard/click focusinput:focus { outline: 2px solid blue; }
:nth-child(n)Pseudo-classNth child elementtr:nth-child(even) { background: #f5f5f5; }
:not(sel)Pseudo-classNot matching selp:not(.special) { font-size: 14px; }
::beforePseudo-elementVirtual content before element.icon::before { content: '★'; }
::afterPseudo-elementVirtual content after element.req::after { content: ' *'; color: red; }
::placeholderPseudo-elementInput placeholder textinput::placeholder { color: #aaa; }
[attr]AttributeHas attribute (any value)img[alt] { border: 1px solid green; }
[attr="val"]AttributeExact attribute valueinput[type="text"] { }
[attr^="val"]AttributeAttribute starts with vala[href^="https"] { }
[attr$="val"]AttributeAttribute ends with vala[href$=".pdf"] { }
[attr*="val"]AttributeAttribute contains val[class*="btn"] { cursor: pointer; }

✅ ✏️ Live Interactive CSS Selectors Playground

Edit the HTML and CSS below and see the result instantly in the live preview. Try all the preset examples to see each selector type in action!

🎨 CSS Selectors Playground — Edit & See Instantly
🖥️ Live Preview
Auto-runs as you type · Press Tab for indentation
💡 How to use: Click any preset to load that selector type, then edit and experiment. Change the selector from p to .highlight to #special and see how each targets different elements!

🧠 CSS Selectors – Yes/No Knowledge Check

Answer each question with Yes (True) or No (False). See your score at the end!

Q1 The class selector in CSS starts with a dot (.) — for example .btn { }.
Q2 An ID selector has lower specificity than a class selector in CSS.
Q3 The pseudo-class selector uses a single colon (:) like a:hover, while pseudo-elements use double colon (::) like p::first-line.
Q4 You can use the same class on multiple HTML elements on the same page.
Q5 The descendant selector nav a (space between) targets ONLY direct children of nav, not deeply nested links.
Q6 The attribute selector a[href^="https"] targets all links whose href attribute STARTS WITH "https".
0/6
CSS Selectors Quiz Score — Well done!

✅ Common CSS Selector Mistakes to Avoid

❌ Mistake 1: Forgetting the dot (.) for class selectors
Wrong: btn { background: blue; } — targets a non-existent HTML <btn> tag.
Correct: .btn { background: blue; } — the dot is required for class selectors.
❌ Mistake 2: Using the same ID on multiple elements
Wrong: Two elements both with id="header" — invalid HTML, causes JavaScript errors.
Correct: Use class="header" for repeated elements and id only for unique landmarks.
❌ Mistake 3: Overusing ID selectors in CSS
IDs have very high specificity (100 points) — this creates specificity wars that are hard to override without !important. Default to classes for CSS; use IDs only for JavaScript or page landmarks.
❌ Mistake 4: Confusing descendant and child selector
nav a (space) targets ALL links inside nav — even deeply nested ones.
nav > a (>) targets ONLY direct children links of nav. Use > when you need to be precise.
❌ Mistake 5: Writing pseudo-elements with single colon
Old syntax: p:before (works in old browsers).
Modern correct: p::before — always use double colon (::) for pseudo-elements in modern CSS.

✅ Frequently Asked Questions (FAQ)

What is a CSS selector?
A CSS selector is the part of a CSS rule that identifies which HTML element(s) to style. It is written before the curly braces. Example: h1 { color: blue; } — here 'h1' is the selector targeting all h1 elements.
What are the main types of CSS selectors?
The main types are: Element selector (p, h1), Class selector (.classname), ID selector (#idname), Universal selector (*), Group selector (h1, h2), Descendant selector (div p), Child selector (div > p), Pseudo-class (:hover, :focus), Pseudo-element (::before, ::after), and Attribute selector (input[type='text']).
What is the difference between a class selector and an ID selector?
A class selector (.classname) can be used on multiple elements — reusable. An ID selector (#idname) must be unique — only one element per page should have that ID. ID has higher specificity (100 points) than class (10 points). Use classes for reusable styles and IDs only when absolutely unique.
What is a CSS pseudo-class?
A CSS pseudo-class targets an element in a specific state, written with a single colon after the selector: a:hover (mouse over), input:focus (focused), li:first-child (first list item). They react to user interaction or document structure without modifying HTML.
What is the difference between pseudo-class and pseudo-element?
Pseudo-class (single colon :) targets an element in a specific STATE — like a:hover. Pseudo-element (double colon ::) targets a specific PART of an element — like p::first-line (first line of text) or div::before (virtual content before the element).
What is a CSS attribute selector?
Attribute selectors target elements based on their HTML attributes using square brackets. Example: input[type='text'] targets only text inputs; a[href^='https'] targets secure links; a[href$='.pdf'] targets PDF links. Very useful for form styling and link targeting.

✍️ About the Author: Pramod Behera

Pramod Behera is a SAP and web development educator with 10+ years of experience in enterprise software and frontend technologies. He founded LearnToSAP.com to help beginners learn SAP, SQL, HTML, and CSS with clear, practical, real-world examples.