What Are CSS Selectors and How Do They Work?

Learn What Are CSS Selectors and How Do They Work? with practical examples, explanations, best practices, and real-world coding techniques.

Try Editor

CSS syntax and selectors are the foundation of writing CSS. Before learning Flexbox, Grid, animations, responsive layouts, or advanced CSS features, you need to understand how CSS identifies elements and applies styles to them.

A selector tells the browser which HTML elements should receive a style, while CSS declarations describe what should change. Once you understand this relationship, CSS becomes much easier to read and write.

The Basic CSS Model

Selector

Identifies the elements you want to style.

Property

Describes what aspect of the element should be changed.

Value

Specifies how the selected property should behave.

What Is CSS Syntax?

CSS syntax is the structure used to write CSS rules. A basic CSS rule contains a selector followed by a declaration block.

p {
  color: blue;
  font-size: 18px;
}

In this example, p is the selector. The declarations inside the braces define the styles that should be applied to matching paragraph elements.

Understanding a CSS Declaration

A CSS declaration consists of a property, a colon, and a value. A semicolon separates declarations.

color: orange;
font-size: 20px;
font-weight: 700;

For example, in color: orange;, color is the property and orange is its value.

What Does a CSS Rule Look Like?

Selector
.card
↓
{
padding: 20px;
background: white;
}

What Is an Element Selector?

An element selector targets HTML elements by their tag name.

p {
  color: #334155;
}

h1 {
  color: #f97316;
}

button {
  padding: 10px 16px;
}

Every matching element receives the specified declarations unless another part of the cascade changes the result.

<h1>Welcome</h1>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<button>Continue</button>

What Is a Class Selector?

A class selector begins with a period and targets elements that contain the specified class.

.card {
  padding: 20px;
  border-radius: 12px;
  background: white;
}
<div class="card">
  <h2>Product</h2>
  <p>Learn more about this product.</p>
</div>

Classes are commonly used for reusable component styles because the same class can be applied to multiple elements.

What Is an ID Selector?

An ID selector begins with # and targets an element by its ID.

#header {
  background: #0f172a;
  color: white;
}
<header id="header">
  <h1>My Website</h1>
</header>

IDs have higher selector specificity than class and element selectors. For reusable component styling, classes are generally more flexible.

Class Selectors vs ID Selectors

Feature Class ID
Syntax .class-name #id-name
Reusable Yes Intended to identify one element
Specificity Lower Higher
Common styling use Components and reusable styles Unique elements and document identification

What Is the Universal Selector?

The universal selector is written using * and can match any element.

* {
  box-sizing: border-box;
}

It is often used for foundational rules, especially when a project wants a consistent box-sizing strategy. Because it can match many elements, use it deliberately rather than placing unnecessary declarations on every element.

How Do Grouped Selectors Work?

Multiple selectors can share the same declaration block by separating them with commas.

h1,
h2,
h3 {
  color: #f97316;
}

This avoids repeating the same declarations across separate rules.

What Is a Descendant Selector?

A descendant selector targets an element that exists somewhere inside another element. It is written by placing selectors next to each other with whitespace between them.

.card p {
  color: #64748b;
}

This targets paragraphs located inside an element with the card class.

What Is the Child Combinator?

The child combinator uses > and targets only direct children.

.card > p {
  color: #64748b;
}

A paragraph nested deeper inside another element would not match this selector.

<div class="card">

  <p>Direct child</p>

  <div>
    <p>Nested paragraph</p>
  </div>

</div>

What Is the Adjacent Sibling Selector?

The adjacent sibling combinator uses +. It selects an element that immediately follows another sibling.

h2 + p {
  margin-top: 0;
}

In this example, the paragraph must immediately follow the h2.

What Is the General Sibling Selector?

The general sibling combinator uses ~. It selects matching siblings that appear later in the same parent.

h2 ~ p {
  color: #64748b;
}

Unlike +, the matching paragraph does not need to be immediately after the heading.

What Are Attribute Selectors?

Attribute selectors target elements based on HTML attributes. They are useful when styling controls according to attributes such as type, disabled, href, or custom data attributes.

input[type="email"] {
  border-color: #2563eb;
}

input[disabled] {
  opacity: 0.6;
}

[data-theme="dark"] {
  background: #0f172a;
}

Common Attribute Selector Patterns

Selector Meaning
[type="email"] Attribute exactly equals a value
[disabled] Attribute exists
[class~="active"] Whitespace-separated attribute value contains a word
[href^="https"] Value starts with the specified text
[href$=".pdf"] Value ends with the specified text

What Are Pseudo-Classes?

A pseudo-class targets an element based on a state, relationship, or condition. Pseudo-classes begin with a single colon.

button:hover {
  background: #ea580c;
}

input:focus {
  border-color: #2563eb;
}

button:disabled {
  opacity: 0.5;
}

li:first-child {
  font-weight: 700;
}

Pseudo-classes are extremely useful for interaction states and structural conditions without requiring additional classes for every state.

What Are Pseudo-Elements?

A pseudo-element represents a particular part of an element or creates generated content. Modern pseudo-element syntax commonly uses two colons.

.title::before {
  content: "→ ";
}

.description::first-line {
  font-weight: 700;
}

.input::placeholder {
  color: #94a3b8;
}

Pseudo-Class vs Pseudo-Element

Type Example Purpose
Pseudo-class :hover Targets a state or condition
Pseudo-element ::before Targets a part or generated content

What Does :is() Do?

The :is() functional pseudo-class allows multiple selector alternatives to be grouped into a single selector.

.content :is(h1, h2, h3) {
  color: #f97316;
}

This can make complicated selector lists easier to read and maintain.

What Does :where() Do?

The :where() functional pseudo-class also groups selector alternatives, but it contributes zero specificity. This makes it particularly useful when you want a reusable selector without increasing specificity.

:where(.card, .panel) h2 {
  margin-top: 0;
}

How Does CSS Specificity Affect Selectors?

When multiple selectors match the same element and declare the same property, specificity is one of the factors the cascade uses to determine which declaration wins.

Element
p
Class
.card
ID
#header

A common beginner mistake is thinking that source order is always enough to determine the winner. CSS first considers the relevant cascade rules, then factors such as specificity and source order when resolving competing declarations.

Simple Specificity Example

p {
  color: blue;
}

.card p {
  color: green;
}

#main-text {
  color: red;
}
<p
  id="main-text"
  class="card-text"
>
  Hello CSS
</p>

Several rules match the paragraph, but they do not have equal specificity. Understanding this prevents the common practice of adding increasingly complicated selectors just to force a style to win.

Combining Multiple Selectors

Selectors can be combined to describe more specific relationships between elements.

.card .title {
  color: #f97316;
}

.navigation > .link {
  padding: 10px;
}

.form input[type="email"] {
  width: 100%;
}

However, more specific does not automatically mean better. Keep selectors as simple as possible while still expressing the required relationship.

How Do Selectors Work with Multiple Classes?

You can select an element that has multiple classes by combining the class selectors without spaces.

.button.primary {
  background: #f97316;
}

.card.featured {
  border-color: #f97316;
}

The absence of whitespace is important. .button.primary means one element must have both classes, while .button .primary means an element with the primary class exists somewhere inside an element with the button class.

A Common Selector Confusion

Two Classes on One Element

.button.primary {
  color: white;
}

Matches an element containing both classes.

Nested Element

.button .primary {
  color: white;
}

Matches a primary element inside a button element.

Selector Naming Best Practices

Good selector naming makes large CSS projects easier to maintain. Prefer names that describe a component's role or purpose instead of permanently describing its current color or visual appearance.

Less Flexible

.orange-box {
  background: orange;
}

More Meaningful

.alert {
  background: orange;
}

The second class name describes the component's purpose. If the design later changes its background color, the class name still makes sense.

Avoid Extremely Deep Selectors

Deep selectors can make CSS tightly dependent on the current HTML structure and increase specificity unnecessarily.

/* Harder to maintain */

.page main .content .card .header h2 span {
  color: orange;
}

A component-oriented class is often easier to understand:

.card-title-accent {
  color: orange;
}

Selector Performance: What Actually Matters?

Developers sometimes spend too much time trying to find the shortest possible selector for performance reasons. In modern applications, maintainability and predictable behavior are usually more important than micro-optimizing ordinary selectors.

Extremely broad selectors, unnecessary descendant chains, and large amounts of unused CSS can still make a stylesheet harder to manage. Prefer selectors that are clear, appropriately scoped, and easy to reason about.

Common CSS Syntax Mistakes

Missing Braces

.card
  color: red;

Declarations need to be enclosed in a declaration block.

Missing Colon

color red;

A declaration requires a colon between the property and value.

Incorrect Class Syntax

card {
  color: red;
}

This targets an element named card, not a class. A class selector requires .card.

Confusing Descendant and Multiple Classes

.button.primary { }

.button .primary { }

These selectors represent two completely different relationships.

A Practical Navigation Example

The following example demonstrates element selectors, class selectors, descendant selectors, child selectors, hover states, and attribute selectors together.

.navigation {
  display: flex;
  gap: 1rem;
}

.navigation > .link {
  color: #334155;
  text-decoration: none;
}

.navigation > .link:hover {
  color: #f97316;
}

.navigation > .link.active {
  font-weight: 700;
}

.navigation a[href^="https"] {
  text-decoration: underline;
}

A Practical Form Example

.form {
  display: grid;
  gap: 1rem;
}

.form label {
  font-weight: 600;
}

.form input[type="email"],
.form input[type="password"] {
  width: 100%;
  padding: 12px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
}

.form input:focus {
  border-color: #2563eb;
  outline: 3px solid rgb(37 99 235 / 20%);
}

.form button:disabled {
  opacity: 0.5;
}

CSS Selector Cheat Sheet

Selector Purpose Example
p Element All paragraphs
.card Class Elements with class card
#header ID Element with header ID
* Universal Any element
.card p Descendant Paragraph anywhere inside card
.card > p Child Direct paragraph child
h2 + p Adjacent sibling Immediate paragraph sibling
h2 ~ p General sibling Later paragraph siblings
input[type="email"] Attribute Email inputs
:hover Pseudo-class Hover state
::before Pseudo-element Generated content / element part

How to Write Maintainable CSS Selectors

Prefer Classes for Reusable Components

Classes are flexible and allow the same component styles to be reused.

Keep Selectors Simple

Avoid unnecessarily deep selector chains.

Use Meaningful Names

Describe the role or purpose of the component where appropriate.

Avoid Specificity Problems

Do not repeatedly increase specificity just to override previous rules.

Use Attribute Selectors Deliberately

They are useful when the attribute itself is part of the styling requirement.

Use Pseudo-Classes for States

Express interaction states such as hover, focus, checked, and disabled directly in CSS.

Key Takeaways

A CSS rule combines a selector with a declaration block.

A declaration contains a property and value separated by a colon.

Element selectors target HTML tags, class selectors target reusable classes, and ID selectors target elements by ID.

The universal selector * can match any element.

Combinators such as whitespace, >, +, and ~ describe relationships between elements.

Attribute selectors target elements according to their attributes and values.

Pseudo-classes represent states and conditions, while pseudo-elements represent specific parts or generated content.

Selector specificity affects which competing declaration wins in the cascade.

Simple, meaningful selectors are usually easier to maintain than deeply nested selector chains.

Understanding CSS selectors is essential before moving into advanced layout, responsive design, and large-scale CSS architecture.

Code Examples

css
/* Basic CSS syntax */

p {
  color: #334155;
  font-size: 18px;
  line-height: 1.6;
}
    
css
/* Common selectors */

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

/* Class */
.card {
  padding: 20px;
}

/* ID */
#header {
  background: #0f172a;
}

/* Universal */
* {
  box-sizing: border-box;
}

/* Attribute */
input[type="email"] {
  border-color: #2563eb;
}
    
css
/* Combinators */

/* Descendant */
.card p {
  color: #64748b;
}

/* Direct child */
.card > p {
  margin-top: 0;
}

/* Adjacent sibling */
h2 + p {
  margin-top: 0;
}

/* General sibling */
h2 ~ p {
  color: #64748b;
}
    
css
/* Pseudo-classes */

.button:hover {
  background: #ea580c;
}

.button:focus-visible {
  outline: 3px solid #2563eb;
  outline-offset: 3px;
}

.input:focus {
  border-color: #2563eb;
}

.button:disabled {
  opacity: 0.5;
}
    
css
/* Pseudo-elements */

.title::before {
  content: "→ ";
}

.title::after {
  content: " ←";
}

.input::placeholder {
  color: #94a3b8;
}

.article::first-letter {
  font-size: 2rem;
  font-weight: 700;
}
    
css
/* Functional selectors */

.content :is(h1, h2, h3) {
  color: #f97316;
}

:where(.card, .panel) p {
  line-height: 1.7;
}

/*
:is() can group alternatives.

:where() also groups alternatives
but contributes zero specificity.
*/
    
html
<!DOCTYPE html>
<html>
<head>

  <style>

    *,
    *::before,
    *::after {
      box-sizing: border-box;
    }

    body {
      margin: 0;
      font-family: Arial, sans-serif;
      background: #f1f5f9;
      color: #1e293b;
    }

    .container {
      width: min(
        calc(100% - 2rem),
        800px
      );

      margin-inline: auto;
      padding-block: 3rem;
    }

    .card {
      padding: 1.5rem;

      border:
        1px solid #cbd5e1;

      border-radius: 12px;

      background: white;
    }

    .card > h2 {
      margin-top: 0;
    }

    .card p {
      color: #64748b;
      line-height: 1.7;
    }

    .button {
      padding:
        0.75rem 1rem;

      border: 0;
      border-radius: 8px;

      background: #f97316;
      color: white;

      font: inherit;
      cursor: pointer;
    }

    .button:hover {
      background: #ea580c;
    }

    .button:focus-visible {
      outline:
        3px solid #2563eb;

      outline-offset: 3px;
    }

  </style>

</head>

<body>

  <main class="container">

    <article class="card">

      <h2>
        CSS Selectors
      </h2>

      <p>
        CSS selectors tell the browser
        which elements should receive
        particular styles.
      </p>

      <button class="button">
        Learn More
      </button>

    </article>

  </main>

</body>
</html>
    

Pro Tip

When a CSS rule is not applying, do not immediately make the selector more complicated. First check whether the selector actually matches the element, then inspect specificity and the cascade in DevTools. Simple class-based selectors are usually easier to maintain than deep chains built only to force an override.

More CSS lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.