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.
Anatomy of a CSS Rule
Every CSS declaration follows the same structure. Understanding this pattern makes every rule you write click into place.
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
{ }. A
block can contain one or many declarations.property: value; pair. Always
end with a semicolon — omitting it causes the next declaration to fail silently.color,
font-size, margin, background.
red,
16px, #264de4, bold, 1.5.
/* … */. 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.
/* 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.
/* 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.
/* 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).
/* CSS */
#hero {
background: linear-gradient(135deg, #264de4, #4a8af4);
color: #fff;
padding: 80px 40px;
text-align: center;
}
/* HTML */
<section id="hero">Welcome!</section>
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:
/* 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;
}
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:
article p { … }
ul > li { … }
h2 + p { … }
h2 ~ p { … }
/* 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.
/* [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 :.
/* 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:
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 ::.
/* ::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;
}
:: 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):
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 */
!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.
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.
Quick Check — Chapter 2
.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.
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.
: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.
—
[attr] — has the attribute at all—
[attr="val"] — exact match—
[attr^="val"] — starts with—
[attr$="val"] — ends with—
[attr*="val"] — containsTo style PDF links:
a[href$=".pdf"] { color: red; } — this targets
any <a> whose href ends
with .pdf.
(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.
class="btn"?href ends with .pdf?- A CSS rule consists of a selector, a declaration block
{ }, and one or more property: value; declarations. - Universal
*, elementp, class.cardand ID#heroare 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.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.