Tutorials CSS Syntax & Selectors
Ch 2 / 60
Chapter 2 Beginner 8 min read CSS

CSS Syntax & Selectors

CSS selectors are the foundation of everything you write in CSS — they decide which HTML elements receive your styles. Master every selector type and you'll never lose a styling battle again.

What you'll learn
The anatomy of a CSS rule: selector, property, value
Universal, element, class and ID selectors
Grouping selectors and descendant selectors
Attribute, pseudo-class and pseudo-element selectors
Combinator selectors (child, sibling, adjacent)
Specificity — how the browser decides which rule wins

Anatomy of a CSS Rule

Every CSS declaration follows the same structure. Understanding this pattern makes every rule you write click into place.

/* selector { property: value; } */

h2 ← Selector — which element(s) to target
{
  color ← Property — what to change
  : ← Colon separates property from value
  #264de4 ← Value — the setting to apply
  ; ← Semicolon ends the declaration
} ← Closing brace ends the rule block
Selector
Targets which HTML element(s) the rule applies to. Can be a tag name, class, ID, attribute, pseudo-class, or any combination.
Declaration Block
Everything inside the curly braces { }. A block can contain one or many declarations.
Declaration
A single property: value; pair. Always end with a semicolon — omitting it causes the next declaration to fail silently.
Property
The CSS attribute to modify — e.g. color, font-size, margin, background.
Value
The setting for the property — e.g. red, 16px, #264de4, bold, 1.5.
CSS Comments
CSS comments are written between /* … */. They are ignored by the browser and are great for explaining your code. There are no single-line comments in CSS — // does not work.

Basic Selectors

These are the four foundational selectors every CSS developer uses daily.

1. Universal Selector *

Targets every element on the page. Most commonly used in CSS resets.

CSS
/* Applies to every element */
* {
  box-sizing: border-box;
  margin:     0;
  padding:    0;
}

2. Element (Type) Selector

Targets all elements of a given HTML tag. Applies broadly — use for base styles like headings and body text.

CSS
/* Targets all <p> elements */
p {
  font-size:   16px;
  line-height: 1.7;
  color:       #52524a;
}

/* Targets all <h1> elements */
h1 {
  font-size:   2.5rem;
  font-weight: 700;
}

3. Class Selector .className

Targets elements with a matching class attribute. A class can be applied to multiple elements, and one element can have multiple classes. This is the most-used selector in real projects.

HTML + CSS
/* CSS */
.card {
  background:    #fff;
  border-radius: 12px;
  padding:       24px;
  box-shadow:    0 4px 16px rgba(0,0,0,.1);
}

.text-blue {
  color: #264de4;
}

/* HTML — multiple classes on one element */
<div class="card text-blue">Hello World</div>

4. ID Selector #idName

Targets a single element with a matching id attribute. An ID must be unique on a page — never reuse the same ID. IDs have higher specificity than classes, so use them sparingly in CSS (they're more suited for JavaScript hooks).

HTML + CSS
/* CSS */
#hero {
  background: linear-gradient(135deg, #264de4, #4a8af4);
  color:      #fff;
  padding:    80px 40px;
  text-align: center;
}

/* HTML */
<section id="hero">Welcome!</section>
Class vs ID — Quick Rule
Use classes for styling (reusable, multiple elements). Use IDs for JavaScript targeting and anchor links (href="#hero"). Prefer classes in CSS to keep specificity low and styles predictable.

All Selector Types — Quick Reference

CSS has many selector types. Here is a complete reference of all categories with examples:

Selector Name What it targets Example
* Universal Every element on the page * { margin: 0; }
p Element / Type All <p> elements p { color: #555; }
.card Class All elements with class="card" .card { padding: 20px; }
#hero ID The element with id="hero" (unique) #hero { background: blue; }
h1, h2, p Grouping All h1, h2 and p elements h1, h2 { font-family: sans-serif; }
div p Descendant All <p> inside any <div> nav a { color: white; }
div > p Child Direct <p> children of <div> only ul > li { list-style: none; }
h1 + p Adjacent Sibling First <p> immediately after <h1> h1 + p { font-size: 1.1rem; }
h1 ~ p General Sibling All <p> siblings following <h1> h2 ~ p { margin-top: 8px; }
[type="text"] Attribute Elements with a matching attribute input[type="text"] { border: 1px solid #ccc; }
a:hover Pseudo-class An element in a specific state a:hover { color: #264de4; }
p::first-line Pseudo-element A specific part of an element p::first-line { font-weight: bold; }

Grouping & Descendant Selectors

Two patterns you'll use in almost every stylesheet:

CSS
/* Grouping — apply same styles to multiple selectors */
h1, h2, h3, h4 {
  font-family: 'Clash Display', sans-serif;
  line-height: 1.2;
  color:       #1a1a14;
}

/* Descendant — target elements nested inside another */
nav a {
  /* Targets ALL <a> tags anywhere inside <nav> */
  color:           #fff;
  text-decoration: none;
  font-weight:      500;
}

/* Child — only DIRECT children, not deeper descendants */
ul > li {
  list-style: none;
  padding:    8px 0;
}
Common Mistake
div p (descendant) vs div > p (child) are easy to confuse. The descendant selector matches any <p> nested inside a <div>, however deeply. The child selector only matches direct children.

Combinator Selectors

Combinators express the relationship between two selectors. There are four types:

(space)
Descendant
Matches any element that is a descendant (child, grandchild, etc.) of the first element.
article p { … }
>
Child
Matches elements that are direct children only — not grandchildren or deeper.
ul > li { … }
+
Adjacent Sibling
Matches the element immediately following the first — they must share the same parent.
h2 + p { … }
~
General Sibling
Matches all sibling elements that follow the first element (not just the immediate one).
h2 ~ p { … }
CSS
/* Adjacent sibling — style the paragraph right after an h2 */
h2 + p {
  font-size:   1.1rem;
  color:       #4a8af4;
  margin-top:  0;
}

/* General sibling — all paragraphs following a heading */
h2 ~ p {
  padding-left: 16px;
  border-left:  3px solid #264de4;
}

Attribute Selectors

Attribute selectors target elements based on the presence or value of their HTML attributes — incredibly useful for styling form inputs, links and custom data attributes.

CSS
/* [attr]   — has the attribute */
input[required] { border-color: red; }

/* [attr="val"]   — exact value match */
input[type="email"] { padding-left: 36px; }

/* [attr^="val"]  — value STARTS with "val" */
a[href^="https"] { color: #22c55e; }

/* [attr$="val"]  — value ENDS with "val" */
a[href$=".pdf"] { color: #ef4444; }

/* [attr*="val"]  — value CONTAINS "val" */
a[href*="k2infocom"] { font-weight: 600; }

/* [attr~="val"]  — whitespace-separated list contains "val" */
p[class~="highlight"] { background: yellow; }

Pseudo-class Selectors

Pseudo-classes target elements in a specific state or by their position in the DOM. They are written with a single colon :.

CSS
/* State pseudo-classes */
a:hover   { color: #264de4; text-decoration: underline; }
a:visited { color: #a855f7; }
a:focus   { outline: 2px solid #264de4; }

input:focus    { border-color: #264de4; box-shadow: 0 0 0 3px rgba(38,77,228,.2); }
input:disabled { opacity: .5; cursor: not-allowed; }
input:checked  { accent-color: #264de4; }

/* Structural pseudo-classes */
li:first-child    { font-weight: 700; }
li:last-child     { border-bottom: none; }
li:nth-child(2n)  { background: rgba(38,77,228,.05); } /* even rows */
li:nth-child(odd) { background: rgba(0,0,0,.03); }       /* odd rows */

p:not(.intro) { font-size: 15px; }  /* negation */

Common pseudo-classes at a glance:

:hover
Mouse is over the element
:focus
Element has keyboard/click focus
:active
Element is being clicked
:visited
Link has been visited
:checked
Checkbox/radio is checked
:disabled
Form element is disabled
:first-child
First child of its parent
:last-child
Last child of its parent
:nth-child(n)
nth child — accepts formulas
:not(selector)
Excludes matching elements
:empty
Element has no children
:is()
Matches any in a list

Pseudo-element Selectors

Pseudo-elements target a specific part of an element — such as its first line or first letter — or insert virtual content before/after an element. They are written with a double colon ::.

CSS
/* ::before — inserts content BEFORE the element */
.quote::before {
  content: '"';
  font-size: 2em;
  color: #264de4;
}

/* ::after — inserts content AFTER the element */
.required::after {
  content: ' *';
  color: red;
}

/* ::first-line — styles only the first line of a paragraph */
p::first-line {
  font-weight: 700;
  font-size:   1.05em;
}

/* ::first-letter — styles the very first character */
p::first-letter {
  font-size:   3em;
  float:       left;
  line-height: 0.8;
  margin-right: 8px;
  color:        #264de4;
}

/* ::placeholder — styles input placeholder text */
input::placeholder {
  color:      #a3a39a;
  font-style: italic;
}

/* ::selection — styles user-highlighted text */
::selection {
  background: #264de4;
  color:      #fff;
}
:: vs :
CSS3 uses double colon :: for pseudo-elements (::before, ::after) to distinguish them from pseudo-classes. Single colon :before still works in most browsers for backwards compatibility, but ::before is the correct modern syntax.

Specificity — How the Browser Decides

When two rules target the same element, the browser applies the one with the higher specificity score. Think of it as a four-digit number (inline, IDs, classes, elements):

style="color:red"
Inline style attribute
1,0,0,0
#header
ID selector
0,1,0,0
.card / [type] / :hover
Class, attribute, pseudo-class
0,0,1,0
p / h1 / ::before
Element, pseudo-element
0,0,0,1
CSS — Specificity Examples
p              { color: black;  } /* score: 0,0,0,1 */
.intro         { color: blue;   } /* score: 0,0,1,0  ← wins over p */
#main .intro   { color: green;  } /* score: 0,1,1,0  ← wins over .intro */
                                  /* inline style wins over all of these */
Avoid !important
!important forces a declaration to win regardless of specificity. It breaks the natural cascade and makes debugging painful — treat it as a last resort, not a shortcut.
Free Resource
CSS3 Selectors Cheat Sheet — All Selector Types
A printable one-page reference covering every CSS selector type with syntax, examples and specificity scores.
Download PDF

Try It Yourself

The editor below demonstrates several selector types at once. Edit the CSS and watch the preview update live — try changing the :hover colour or the nth-child pattern.

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js — all in one industry-ready curriculum. Build real projects with AI-powered tools and get placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5 CSS3 JavaScript React.js Node.js Tailwind CSS AI Tools

Quick Check — Chapter 2

Questions & Answers
A class selector (.card) can be applied to multiple elements and reused throughout a page. It has a specificity score of 0,0,1,0.

An ID selector (#hero) must be unique on a page — there should only ever be one element with a given ID. It has a higher specificity score of 0,1,0,0.

Best practice: use classes for all styling; reserve IDs for JavaScript targets and anchor links.
A descendant selector (nav a) matches any <a> that is nested inside a <nav> — no matter how deeply nested (child, grandchild, etc.).

A child selector (nav > a) matches only <a> elements that are direct children of <nav>. Elements nested two or more levels deep are not matched.
Pseudo-classes (single colon, e.g. :hover, :first-child) target an element when it is in a particular state or occupies a specific position in the DOM. They do not create new HTML — they style existing elements conditionally.

Pseudo-elements (double colon, e.g. ::before, ::first-line) target a specific part of an element, or insert virtual content. ::before and ::after require a content property to render anything.
Attribute selectors target elements based on the presence or value of an HTML attribute. They are written inside square brackets:

— [attr] — has the attribute at all
— [attr="val"] — exact match
— [attr^="val"] — starts with
— [attr$="val"] — ends with
— [attr*="val"] — contains

To style PDF links: a[href$=".pdf"] { color: red; } — this targets any <a> whose href ends with .pdf.
Specificity is calculated as a four-digit score (inline, IDs, classes/attributes/pseudo-classes, elements/pseudo-elements):

— Inline style: 1,0,0,0 (highest)
— ID selector #id: 0,1,0,0
— Class .cls, attribute [attr], pseudo-class :hover: 0,0,1,0
— Element p, pseudo-element ::before: 0,0,0,1 (lowest)

When two rules have the same specificity, the one that appears later in the stylesheet wins (source order). !important overrides all of this — avoid it.
Multiple Choice Questions
Question 1 of 5
Which selector targets an element with class="btn"?
Question 2 of 5
Which combinator selects only direct children?
Question 3 of 5
Which specificity score is highest?
Question 4 of 5
Which attribute selector targets links whose href ends with .pdf?
Question 5 of 5
Which pseudo-element inserts content before an element without adding HTML?
Chapter Summary
  • A CSS rule consists of a selector, a declaration block { }, and one or more property: value; declarations.
  • Universal *, element p, class .card and ID #hero are the four foundational selectors.
  • Use class selectors for styling (reusable). Reserve ID selectors for JavaScript hooks and anchor links.
  • Combinator selectors — descendant (space), child (>), adjacent sibling (+), general sibling (~) — express DOM relationships.
  • Attribute selectors [attr$=".pdf"] target elements by their HTML attributes — perfect for forms and links.
  • Pseudo-classes (single colon :) target elements by state or position; pseudo-elements (double colon ::) target parts of elements or inject content.
  • Specificity is scored as (inline, IDs, classes, elements). Higher score wins; equal scores resolve by source order.
~8 min read
Beginner level
Chapter 2 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel