CSS Selectors

Beginner
14 min read
Updated: Nov 2026
5 examples
59 selector guides

Definition and Usage

CSS selectors are patterns that choose which HTML elements receive styles. They sit before the curly braces in a rule and answer one question: who should this CSS apply to?

Selector vs property

A selector picks the elements (.btn). A property chooses what to change (background-color). A value sets how (#2563eb). Together they form a rule: .btn { background-color: #2563eb; }.

What should beginners learn first?

Master .class, element selectors (element), #id sparingly, descendant combinators, and :hover / :focus for interaction. Those cover most CSS tutorial work before attributes and advanced pseudo-classes.

Hub vs single-selector pages

This page teaches how selectors work in a CSS tutorial. Each name in the index links to a focused guide (for example CSS .class Selector). For the declarations you apply after matching, see CSS Properties; for responsive conditions, see Media Queries.

Prefer classes.

Use .class for reusable components. Reserve #id for unique landmarks or script hooks—high specificity makes overrides harder.

Keep selectors short.

.card-title beats deep chains like div div h3 span. Long selectors are fragile when HTML changes.

Match HTML first.

Selectors only work if the markup has the tags, classes, or attributes you target. Write clear HTML, then style it.

CSS Syntax

Every rule pairs a selector with a declaration block:

CSS
/* Element */
p { color: #334155; }

/* Class */
.highlight { background: #fef08a; }

/* ID */
#footer { text-align: center; }

/* Pseudo-class */
a:hover { text-decoration: underline; }

/* Combinator + attribute */
nav a[href^="https"] { color: #059669; }

Core CSS Concepts

Selector families you will use throughout this CSS tutorial:

CategoryExampleTargets
ElementpAll matching tags
Class.cardElements with that class
ID#mainOne unique element
Combinatornav aLinks inside <nav>
Pseudo-classa:hoverState or position
Pseudo-element::beforeA part of an element
Attribute[href^="https"]Matching attribute values

Specificity (who wins)

When two rules conflict, the browser compares specificity, then source order:

  • Inline style — highest (avoid overusing)
  • ID selectors — #nav beats classes
  • Classes, attributes, pseudo-classes — .btn, [open], :hover
  • Elements and pseudo-elements — p, ::before

Prefer low-specificity selectors—especially classes—so overrides stay easy.

When to use which selector

JobPrefer
Reusable components.class on buttons, cards, badges
Base typographyElement selectors: p, h1–h6
Unique landmarks#id sparingly (skip links, page regions)
Scoped menusnav a or nav > ul > li
Forms & links:focus, :invalid, :hover, :checked

How to Use Selectors in CSS

A practical workflow for this tutorial track:

  1. Write clear HTML with meaningful tags and classes.
  2. Start with element selectors for base text styles.
  3. Add classes for components you reuse.
  4. Use combinators only when nesting truly matters (nav a).
  5. Add :hover / :focus for interaction; keep focus visible.
  6. Open a single-selector page from the index when you need details and try-it demos.

Live Preview

Toggle the .highlight class on matching items—same idea as writing .highlight { … } in CSS.

Only elements that already have the class name in HTML can match .highlight.

Preview
Item A — has class="highlight"
Item B — no highlight class
Item C — has class="highlight"

CSS Examples

Five starter patterns from a CSS tutorial: basic selectors, combinators, :hover, attributes, and ::before.

Example 1 — Element, class & ID

Three fundamental ways to target HTML elements.

CSS
p { color: #334155; }
.highlight { background: #fef08a; }
#footer { text-align: center; }
.class Tutorial

How It Works

  1. p targets every paragraph element.
  2. .highlight targets any element with that class.
  3. #footer targets the single element with that id.
  4. Prefer classes for styles you reuse across the page.

Example 2 — Descendant combinator

Style links only inside a navigation block.

CSS
nav a {
  color: #2563eb;
  text-decoration: none;
}

How It Works

  1. Space between nav and a is the descendant combinator.
  2. Only links inside nav match—body links stay untouched.
  3. Child (>) is stricter: only direct children.
  4. Scope styles with structure instead of extra classes when nesting is clear.

Example 3 — :hover pseudo-class

Give visual feedback when the pointer is over a link.

CSS
a:hover {
  color: #0f766e;
  text-decoration: underline;
}
:hover Tutorial

How It Works

  1. :hover applies while the pointer rests over the element.
  2. Pair with :focus so keyboard users get the same feedback.
  3. Do not hide essential actions behind hover alone on touch devices.
  4. LVHA order for links: :link, :visited, :hover, :active.

Example 4 — Attribute selector

Style external HTTPS links differently.

CSS
a[href^="https"] {
  color: #059669;
}

How It Works

  1. [href^="https"] matches when the value starts with that string.
  2. ^= is the “starts with” attribute operator.
  3. Internal paths without https stay on default styles.
  4. Also explore $= (ends with) and *= (contains).

Example 5 — ::before pseudo-element

Insert decorative content before an element.

CSS
.note::before {
  content: "Note: ";
  font-weight: 700;
}
::before Tutorial

How It Works

  1. ::before creates a virtual first child.
  2. content is required for the pseudo-element to appear.
  3. Two colons mark a pseudo-element; one colon marks a pseudo-class.
  4. Use for decoration—keep meaningful text in real HTML.

CSS Selector Tutorial Index

Search by selector name or browse by category. Every row links to a full guide with try-it examples and FAQs (59 tutorials).

Basic Selectors

5 tutorials

Target elements by tag name, class, ID, or every element on the page.

SelectorDescriptionTutorial
elementTargets all instances of an HTML element — e.g. p styles every paragraph.Try it
*Applies styles to all elements. Common in CSS resets.Try it
.classSelects elements with a matching class attribute — e.g. .highlight.Try it
element.classCombines tag and class — e.g. p.note targets <p class="note">.Try it
#idTargets one element with a unique id — e.g. #footer.Try it

Combinators

5 tutorials

Style elements based on their relationship to other elements in the DOM.

SelectorDescriptionTutorial
element elementNested descendants — div p styles <p> inside any <div>.Try it
element > elementDirect children only — div > p skips deeper nested paragraphs.Try it
element + elementImmediate next sibling — h2 + p styles the first <p> after an <h2>.Try it
element ~ elementAny following sibling — p ~ ul styles <ul> siblings after a <p>.Try it
element, elementComma-separated list — h1, h2, p shares one rule block.Try it

Pseudo-Classes

35 tutorials

Target element states, positions, and form validation — prefixed with a single colon.

SelectorDescriptionTutorial
:activeStyles an element while the user is pressing or clicking it.Try it
:checkedTargets checked checkboxes, radio buttons, and selected options.Try it
:defaultThe default option in a form control group.Try it
:disabledForm elements that cannot be interacted with.Try it
:emptyElements with no children and no text content.Try it
:enabledForm elements that are active and editable.Try it
:first-childThe first child among its siblings.Try it
:first-of-typeThe first element of its type within its parent.Try it
:focusElements receiving keyboard or pointer focus.Try it
:fullscreenThe element currently displayed in fullscreen mode.Try it
:has()Parent-aware selector — style based on descendants or siblings.Try it
:hoverWhen the pointer is over an element.Try it
:in-rangeInputs whose value falls within min/max range.Try it
:indeterminateCheckboxes or radios in a mixed/indeterminate state.Try it
:invalidForm fields that fail validation constraints.Try it
:lang()Elements with a given language code — e.g. p:lang(es).Try it
:last-childThe last child among its siblings.Try it
:last-of-typeThe last element of its type within its parent.Try it
:linkUnvisited hyperlinks.Try it
:not()Elements that do not match the argument selector.Try it
:nth-child()Elements by index among siblings — e.g. li:nth-child(2).Try it
:nth-last-child()Elements counted from the end among siblings.Try it
:nth-last-of-type()Elements of a type counted from the end.Try it
:nth-of-type()Elements of a type by index — e.g. p:nth-of-type(2).Try it
:only-childThe sole child of its parent.Try it
:only-of-typeThe only element of its type among siblings.Try it
:optionalInputs without the required attribute.Try it
:out-of-rangeInputs with values outside the allowed range.Try it
:read-onlyNon-editable form fields.Try it
:read-writeEditable user-input elements.Try it
:requiredForm fields that must be filled before submit.Try it
:rootThe document root — usually <html> — ideal for CSS variables.Try it
:targetThe element matching the URL fragment — e.g. #news:target.Try it
:validForm fields that pass validation.Try it
:visitedHyperlinks the user has already visited.Try it

Pseudo-Elements

7 tutorials

Style specific parts of an element — prefixed with two colons.

SelectorDescriptionTutorial
::beforeInserts generated content before an element's children.Try it
::afterInserts generated content after an element's children.Try it
::first-letterStyles the first letter of a block-level element.Try it
::first-lineStyles the first line of text in a block.Try it
::markerThe bullet or number of a list item.Try it
::placeholderPlaceholder text inside inputs and textareas.Try it
::selectionText highlighted by the user.Try it

Attribute Selectors

7 tutorials

Match elements by the presence or value of HTML attributes.

SelectorDescriptionTutorial
[attribute]Elements that have a given attribute — e.g. [target].Try it
[attribute=value]Exact attribute value — e.g. [type="submit"].Try it
[attribute~=value]Attribute contains a word in a space-separated list.Try it
[attribute|=value]Value equals or starts with value followed by a hyphen.Try it
[attribute^=value]Attribute value starts with a string — e.g. [href^="https"].Try it
[attribute$=value]Attribute value ends with a string — e.g. [href$=".pdf"].Try it
[attribute*=value]Attribute value contains a substring anywhere.Try it

Edge Cases & Pitfalls

Most selector mistakes are over-specific IDs, deep chains, or missing focus styles.

#id

Overusing IDs for styling

High specificity makes overrides painful. Prefer classes for visual styles.

nest

Deep descendant chains

div div div p breaks when markup shifts. Use a class on the real target instead.

*

Universal selector everywhere

* touches every element. Fine in a careful reset; risky as a default styling tool.

:h

Hover-only interactions

Touch devices may never hover. Keep actions visible and style :focus too.

::

Missing content on ::before

Pseudo-elements need a content value (even "") to render.

a11y

Removing :focus outlines

Never drop focus styles without a visible replacement. Keyboard users depend on them.

Browser Support

Core CSS selectors—element, class, ID, combinators, :hover, :focus, and basic attribute selectors—are Baseline CSS. Newer selectors like :has() vary; each guide notes its own support.

✓ Baseline · Widely available

CSS selectors

Essential selectors work in all major browsers. Check individual tutorials for newer pseudo-classes.

100% core selectors
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
Core CSS selectors Universal

Bottom line: Learn .class, element, combinators, and :hover/:focus first—they are production-safe. Newer selectors document compatibility on their own pages.

Key Takeaways

  • Selectors choose which elements a CSS rule styles.
  • Start with .class, elements, then :hover / :focus.
  • Specificity: IDs > classes > elements—prefer lower when you can.
  • Next: .class, :hover, or the index above.

One line: Selectors target HTML for styling—favor classes, keep them short, learn specificity, then open guides from the index.

Frequently Asked Questions

CSS selectors are patterns that tell the browser which HTML elements to style. They appear before the declaration block: selector { property: value; }. Examples include p, .card, #header, and a:hover.
A class selector (.name) can match many elements and is reusable. An ID selector (#name) should match only one element per page. Prefer classes for most styling; reserve IDs for unique landmarks or JavaScript hooks.
Specificity decides which rule wins when multiple selectors target the same element. IDs beat classes, classes beat elements, and inline styles beat stylesheet rules. Lower specificity is easier to maintain.
Pseudo-classes (:hover, :focus) describe element state or position. Pseudo-elements (::before, ::first-letter) style a part of an element. Use one colon for pseudo-classes and two for pseudo-elements.
Combinators connect selectors to express relationships: descendant (space), child (>), adjacent sibling (+), and general sibling (~). They style elements based on where they sit in the HTML.
Open the .class tutorial first, then element and :hover. Use the searchable index for any of the selector guides, then pair selectors with CSS Properties to finish each rule.

Start your first selector tutorial

Open .class for reusable styles, or browse the searchable index above.

.class tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful