LearnContact
Lesson 418 min read

CSS Selectors

Learn how CSS selectors target HTML elements using element, class, ID, universal, grouping, descendant, child, sibling, attribute, pseudo-class, and pseudo-element selectors.

Introduction

In the previous lesson, you learned the syntax used to write CSS rules.

You learned that every standard CSS rule begins with a selector.

Now it is time to understand selectors in detail.

Selectors are one of the most important parts of CSS because they decide exactly which HTML elements should receive a style.

Without selectors, the browser would know what style to apply but would not know which elements should receive it.

Write Selector
Browser Searches HTML
Find Matching Elements
Read Declarations
Apply Styles
Display Output
Selectors Choose the Target

The selector answers one important question: Which HTML element or elements should receive these styles?

What are CSS Selectors?

A CSS selector is a pattern used to find and target HTML elements.

After the browser finds elements that match the selector, it applies the declarations written inside the rule.

Basic Selector Example
p {
    color: blue;
}

In this example, p is the selector.

The browser searches the document for every <p> element and applies the blue text color.

HTML
<h1>CSS Selectors</h1>

<p>First paragraph</p>

<p>Second paragraph</p>
Read p Selector
Find First <p>
Find Second <p>
Apply color: blue
Display Both in Blue
SelectorTarget
pAll paragraph elements
h1All level-one headings
.cardElements with class="card"
#headerElement with id="header"
*All elements

Why Do We Need Selectors?

A webpage can contain hundreds or thousands of HTML elements.

Different elements need different styles.

Selectors allow developers to control exactly where CSS rules should apply.

HTML
<h1>Main Heading</h1>

<p>Normal paragraph</p>

<p class="important">
    Important paragraph
</p>

<button>Submit</button>
CSS
h1 {
    color: purple;
}

p {
    color: gray;
}

.important {
    color: red;
}

button {
    background-color: green;
    color: white;
}

Without Precise Selectors

  • Every element may receive the same style.
  • Specific elements are difficult to target.
  • Reusable designs become difficult.
  • Large pages become hard to control.
  • Styles may affect unwanted elements.

With Precise Selectors

  • Target exact elements.
  • Create reusable classes.
  • Style unique sections.
  • Control nested elements.
  • Build maintainable interfaces.
Selectors Give CSS Precision

The better you understand selectors, the more accurately you can control the appearance of a webpage.

Real-World Analogy

Imagine a teacher giving instructions to students in a classroom.

The teacher can give an instruction to everyone, a group of students, one specific student, or students with a particular characteristic.

Classroom InstructionCSS Selector
All studentsUniversal selector
All students in Grade 10Element or class selector
Students in the red teamClass selector
Student with roll number 25ID selector
Students carrying laptopsAttribute selector
Classroom Instructions
Everyone → Stand up

Red Team → Move left

Student #25 → Answer the question

Students with laptops → Open the browser
Similar CSS Targeting
* {
    box-sizing: border-box;
}

.red-team {
    color: red;
}

#student-25 {
    font-weight: bold;
}

[data-device="laptop"] {
    background-color: yellow;
}
Different Targets Need Different Selectors

CSS provides different selector types so you can target elements based on their tag, class, ID, position, relationship, attribute, or state.

Basic Selector Syntax

A selector is written before the declaration block.

Selector Syntax
selector {
    property: value;
}
Real Example
h1 {
    color: blue;
}
Syntax Breakdown
h1 {
│
│   color: blue;
│
}
│
└── Selector

The selector can be simple or complex.

Simple Selectors
p { }

.card { }

#header { }
More Complex Selectors
nav a { }

.card > h2 { }

input[type="email"] { }

button:hover { }
SelectorMeaning
pEvery <p> element
.cardEvery element with class="card"
#headerThe element with id="header"
nav aLinks inside <nav>
button:hoverA button while the pointer is over it

Types of CSS Selectors

CSS provides many selector types for different targeting requirements.

Selector TypeSyntaxPurpose
ElementpTargets HTML elements by tag name
Class.cardTargets elements by class
ID#headerTargets an element by ID
Universal*Targets all elements
Groupingh1, h2Targets multiple selectors
Descendantdiv pTargets nested descendants
Childdiv > pTargets direct children
Adjacent Siblingh2 + pTargets the next sibling
General Siblingh2 ~ pTargets following siblings
Attribute[type="text"]Targets by attribute
Pseudo-Class:hoverTargets a state or condition
Pseudo-Element::first-letterTargets part of an element
Need to Target Element?
Choose Selector Type
Write Selector Pattern
Browser Finds Matches
Apply Declarations

1. Element Selector

The element selector targets HTML elements using their tag name.

Element Selector Syntax
element {
    property: value;
}
Example
p {
    color: blue;
}

This rule selects every <p> element on the page.

HTML
<p>First paragraph</p>

<p>Second paragraph</p>

<p>Third paragraph</p>
More Element Selectors
h1 {
    color: purple;
}

button {
    background-color: green;
}

a {
    color: red;
}
SelectorTargets
h1All <h1> elements
pAll <p> elements
buttonAll <button> elements
imgAll <img> elements
aAll <a> elements
Element Selectors Can Affect Many Elements

If a page contains 100 paragraph elements, the p selector can match all 100 of them.

2. Class Selector

The class selector targets elements that contain a specific class attribute value.

A class selector begins with a dot followed by the class name.

Class Selector Syntax
.class-name {
    property: value;
}
HTML
<p class="highlight">
    Important paragraph
</p>

<p>
    Normal paragraph
</p>

<div class="highlight">
    Important box
</div>
CSS
.highlight {
    background-color: yellow;
}

The class can be reused on different elements.

Reusable Class
<h2 class="success">Payment Successful</h2>

<p class="success">Your order is confirmed.</p>

<button class="success">Continue</button>
CSS
.success {
    color: green;
}
Classes Are Reusable

The same class can be added to many elements, making class selectors ideal for reusable styles.

3. ID Selector

The ID selector targets an element using its id attribute.

An ID selector begins with a hash symbol followed by the ID value.

ID Selector Syntax
#id-name {
    property: value;
}
HTML
<header id="main-header">
    Welcome to PrograMinds
</header>
CSS
#main-header {
    background-color: purple;
    color: white;
    padding: 20px;
}

Class Selector

  • Starts with a dot.
  • Designed for reusable grouping.
  • Can be shared by many elements.
  • Example: .card

ID Selector

  • Starts with a hash symbol.
  • Identifies a specific element.
  • An ID should be unique in a document.
  • Example: #main-header
Keep IDs Unique

An id value should identify one unique element in the HTML document.

4. Universal Selector

The universal selector uses an asterisk and can match all elements.

Universal Selector Syntax
* {
    property: value;
}
Common Example
* {
    box-sizing: border-box;
}

This rule applies box-sizing: border-box to every element.

HTML
<h1>Heading</h1>

<p>Paragraph</p>

<button>Button</button>
Universal Color Example
* {
    color: blue;
}
Use Broad Selectors Carefully

The universal selector can affect a large number of elements, so understand the effect of the declarations you place inside it.

5. Grouping Selector

The grouping selector allows multiple selectors to share the same declarations.

Selectors are separated with commas.

Without Grouping
h1 {
    color: purple;
}

h2 {
    color: purple;
}

h3 {
    color: purple;
}
With Grouping
h1,
h2,
h3 {
    color: purple;
}
HTML
<h1>Main Heading</h1>
<h2>Section Heading</h2>
<h3>Subheading</h3>
<p>Normal paragraph</p>
Read Selector List
Match h1
Match h2
Match h3
Apply Shared Declarations
Grouping Reduces Repetition

When different selectors need exactly the same declarations, grouping can keep the stylesheet shorter and easier to maintain.

Selector Combinators

Combinators describe relationships between selectors.

They allow CSS to target elements based on where they appear relative to other elements.

CombinatorSyntaxRelationship
DescendantA BB anywhere inside A
ChildA > BB directly inside A
Adjacent SiblingA + BB immediately after A
General SiblingA ~ BB siblings after A
Example Structure
<div>
    <h2>Heading</h2>

    <p>First paragraph</p>

    <section>
        <p>Nested paragraph</p>
    </section>

    <p>Last paragraph</p>
</div>
Relationships Make Selectors More Precise

Combinators allow you to target elements according to their position and relationship in the HTML structure.

6. Descendant Selector

The descendant selector targets elements located anywhere inside another element.

A space is written between the selectors.

Descendant Selector Syntax
parent descendant {
    property: value;
}
HTML
<article>
    <p>Direct paragraph</p>

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

<p>Outside paragraph</p>
CSS
article p {
    color: blue;
}

Both paragraphs inside the article match, even though one is nested inside another div.

Descendants Can Be Deeply Nested

The descendant does not need to be a direct child. It can appear at any depth inside the ancestor.

7. Child Selector

The child selector targets only elements that are direct children of another element.

The greater-than symbol is written between the selectors.

Child Selector Syntax
parent > child {
    property: value;
}
HTML
<article>
    <p>Direct child paragraph</p>

    <div>
        <p>Nested paragraph</p>
    </div>
</article>
CSS
article > p {
    color: red;
}

Descendant: article p

  • Matches direct children.
  • Matches deeply nested elements.
  • Searches at any depth.

Child: article > p

  • Matches direct children only.
  • Does not match deeper descendants.
  • More structurally specific.

8. Adjacent Sibling Selector

The adjacent sibling selector targets an element that appears immediately after another element at the same parent level.

A plus symbol is written between the selectors.

Adjacent Sibling Syntax
first + next {
    property: value;
}
HTML
<h2>Section Heading</h2>

<p>First paragraph</p>

<p>Second paragraph</p>
CSS
h2 + p {
    color: red;
}

Only the first paragraph matches because it appears immediately after the <h2>.

Immediate Next Sibling Only

The adjacent sibling selector does not target every following sibling. It targets only the first matching element immediately after the first selector.

9. General Sibling Selector

The general sibling selector targets matching siblings that appear after another element.

A tilde symbol is written between the selectors.

General Sibling Syntax
first ~ sibling {
    property: value;
}
HTML
<h2>Section Heading</h2>

<p>First paragraph</p>

<div>Information Box</div>

<p>Second paragraph</p>

<p>Third paragraph</p>
CSS
h2 ~ p {
    color: purple;
}

Adjacent Sibling: +

  • Targets the immediate next sibling.
  • Only one position is considered.
  • Example: h2 + p

General Sibling: ~

  • Targets matching later siblings.
  • Can match multiple elements.
  • Example: h2 ~ p

10. Attribute Selector

Attribute selectors target elements according to the presence or value of an HTML attribute.

Attribute Selector Syntax
[attribute] {
    property: value;
}
HTML
<input type="text">

<input type="email">

<input type="password">
Target Email Input
input[type="email"] {
    border: 2px solid blue;
}
SelectorMeaning
[disabled]Elements containing disabled
[type="email"]Elements where type is exactly email
[class~="card"]Elements whose class list contains card
[href^="https"]href begins with https
[href$=".pdf"]href ends with .pdf
[href*="example"]href contains example
More Attribute Selectors
input[disabled] {
    background-color: lightgray;
}

a[href^="https"] {
    color: green;
}

a[href$=".pdf"] {
    font-weight: bold;
}
Useful for Forms and Data Attributes

Attribute selectors are especially useful for form controls, links, states, and custom data attributes.

11. Pseudo-Class Selector

A pseudo-class selects an element based on a state, condition, or structural position.

Pseudo-classes begin with a single colon.

Pseudo-Class Syntax
selector:pseudo-class {
    property: value;
}
HTML
<button>
    Move Mouse Over Me
</button>
Hover Example
button {
    background-color: blue;
    color: white;
}

button:hover {
    background-color: green;
}
Pseudo-ClassPurpose
:hoverPointer is over the element
:focusElement has keyboard or input focus
:activeElement is being activated
:checkedCheckbox or radio is checked
:disabledForm control is disabled
:first-childElement is the first child
:last-childElement is the last child
:nth-child()Element matches a structural position
Structural Pseudo-Class
li:first-child {
    color: red;
}

li:last-child {
    color: green;
}
Pseudo-Classes Target Conditions

They allow CSS to respond to interaction, form states, and an element position in the document structure.

12. Pseudo-Element Selector

A pseudo-element targets a specific part of an element or creates a styleable generated box.

Modern pseudo-element syntax normally uses two colons.

Pseudo-Element Syntax
selector::pseudo-element {
    property: value;
}
HTML
<p>
    Cascading Style Sheets control the appearance of webpages.
</p>
First Letter Example
p::first-letter {
    color: red;
    font-size: 40px;
}
Pseudo-ElementTargets
::first-letterFirst letter of text
::first-lineFirst rendered line of text
::beforeGenerated box before content
::afterGenerated box after content
::selectionUser-selected text
::placeholderPlaceholder text in form controls
Before and After
.price::before {
    content: "₹";
}

.required::after {
    content: " *";
    color: red;
}

Pseudo-Class

  • Uses a single colon.
  • Targets a state or condition.
  • Example: :hover
  • Example: :first-child

Pseudo-Element

  • Normally uses two colons.
  • Targets a part or generated box.
  • Example: ::first-letter
  • Example: ::before

Combining Selectors

Selectors can be combined to create more precise targeting patterns.

HTML
<article class="card">
    <h2>CSS Course</h2>

    <p class="description">
        Learn CSS step by step.
    </p>

    <a href="/css">
        Start Learning
    </a>
</article>
Combined Selectors
.card h2 {
    color: purple;
}

.card .description {
    color: gray;
}

.card > a {
    color: green;
}

.card a:hover {
    color: red;
}
SelectorMeaning
.card h2h2 elements anywhere inside .card
.card .description.description elements inside .card
.card > aDirect a children of .card
.card a:hoverLinks inside .card while hovered
button.primarybutton elements with class primary
Avoid Unnecessary Complexity

A selector can be technically valid but still be difficult to understand. Use the simplest selector that reliably targets the intended elements.

Selector Specificity

Sometimes multiple CSS selectors match the same element and try to set the same property.

Specificity is one of the rules the browser uses to determine which declaration wins.

HTML
<p
    id="message"
    class="important"
>
    Welcome to CSS
</p>
Competing Rules
p {
    color: blue;
}

.important {
    color: green;
}

#message {
    color: red;
}

The ID selector has greater specificity than the class selector and element selector, so the text becomes red.

Selector CategoryExampleGeneral Strength
ElementpLower
Class / Attribute / Pseudo-Class.cardHigher
ID#headerHigher still
Inline Stylestyle="..."Very strong in normal author styling
Multiple Rules Match
Compare Importance
Compare Origin and Layer
Compare Specificity
Compare Source Order
Choose Winning Declaration
Specificity Is Part of the Cascade

Specificity is important, but it is not the only rule that decides the final style. Importance, origin, cascade layers, and source order can also affect the result.

How Browser Matches Selectors

The browser parses CSS selectors and determines which elements in the document match each selector.

HTML
<div class="card">
    <h2>CSS Course</h2>
    <p>Learn selectors.</p>
</div>

<div>
    <h2>HTML Course</h2>
</div>
CSS
.card h2 {
    color: purple;
}
Read .card h2
Find Matching h2 Elements
Check for .card Ancestor
Keep Valid Matches
Apply Declarations
Calculate Final Style
ElementMatches .card h2?Reason
CSS Course h2YesIt is an h2 inside .card
ParagraphNoIt is not an h2
HTML Course h2NoIt is not inside .card
Selector Matching Must Succeed

A perfectly valid CSS declaration has no effect when the selector does not match the intended element.

Browser Rendering Flow

Selector matching is an important part of the browser rendering process.

Load HTML
Build DOM
Load CSS
Parse Selectors
Build CSSOM
Match Selectors
Resolve Cascade
Calculate Styles
Calculate Layout
Paint Output
Selector Processing Flow
CSS Selector
      │
      ▼
Parse Selector
      │
      ▼
Search for Matches
      │
      ▼
Check Element Structure
      │
      ▼
Check Classes / IDs / Attributes
      │
      ▼
Check States and Conditions
      │
      ▼
Collect Matching Rules
      │
      ▼
Resolve Cascade
      │
      ▼
Calculate Final Styles
      │
      ▼
Render Page
StagePurpose
Parse SelectorUnderstand the selector pattern
Match ElementsFind elements that satisfy the pattern
Collect RulesGather declarations from matching rules
Resolve CascadeDetermine winning declarations
Calculate StylesCreate final computed values
RenderDisplay the styled result

Real-World Applications

CSS selectors are used throughout modern websites and applications.

Navigation Menus

Target links, active items, nested menus, and hover states.

Cards

Style card titles, descriptions, images, buttons, and variants.

Forms

Target input types, required fields, checked controls, and focus states.

Tables

Style rows, columns, headers, and alternating positions.

E-Commerce

Target product cards, sale badges, prices, and action buttons.

Responsive Components

Apply styles to reusable classes across different layouts.

Learning Platforms

Style lessons, code blocks, sidebars, navigation, and progress states.

Dashboards

Target complex nested components and interface states.

Identify UI Element
Choose Selector
Match Correct Target
Apply Styles
Create Final Interface

Advantages

CSS selectors provide flexible and precise control over webpage styling.

Precise Targeting

Style exactly the elements you need.

Reusability

Classes allow styles to be shared across many elements.

Structural Control

Combinators target elements according to relationships.

Interactive States

Pseudo-classes respond to hover, focus, checked, and other conditions.

Attribute Targeting

Style elements based on HTML attributes and values.

Partial Styling

Pseudo-elements style specific parts or generated boxes.

Maintainability

Well-designed selectors make stylesheets easier to manage.

Scalability

Reusable selector strategies support large interfaces.

Common Beginner Mistakes

Forgetting the Dot for Classes

Write .card in CSS to target class="card".

Forgetting the Hash for IDs

Write #header in CSS to target id="header".

Adding a Dot to Element Selectors

Write p for a paragraph element, not .p unless the HTML actually uses class="p".

Adding a Hash to Class Selectors

#card targets an ID, while .card targets a class.

Reusing the Same ID

An ID value should identify one unique element in the document.

Using IDs for Every Style

Heavy ID usage can create unnecessarily strong and difficult-to-override selectors.

Confusing Descendant and Child Selectors

A space matches descendants at any depth, while > matches direct children only.

Confusing + and ~

+ targets the immediate next sibling, while ~ targets matching later siblings.

Forgetting Commas in Grouping

h1, h2 targets both elements, while h1 h2 means h2 elements inside h1 elements.

Adding Unnecessary Spaces

.card .title and .card.title have different meanings.

Using Invalid Attribute Syntax

Attribute selectors require square brackets.

Forgetting Quotes Around Complex Values

Quoted attribute values are often clearer and safer when values contain special characters.

Confusing Pseudo-Classes and Pseudo-Elements

:hover represents a state, while ::before represents a pseudo-element.

Using :hover for Essential Mobile Functionality

Touch devices may not provide the same hover interaction as pointer devices.

Writing Overly Long Selectors

Deep selector chains are difficult to understand and maintain.

Making Selectors Too Specific

Excessive specificity makes later overrides more difficult.

Assuming Source Order Always Wins

Later declarations do not always win when specificity or other cascade rules differ.

Assuming Specificity Is the Entire Cascade

Importance, origin, layers, specificity, and source order can all affect the winner.

Not Checking Whether the Selector Matches

Valid declarations cannot style an element when the selector does not match it.

Not Inspecting the Browser

Developer tools can show matched, unmatched, and overridden CSS rules.

Best Practices

  • Use the simplest selector that reliably targets the intended element.
  • Use element selectors for broad default styles.
  • Use classes for reusable component styles.
  • Keep class names meaningful.
  • Choose class names based on purpose rather than temporary appearance when possible.
  • Use IDs primarily when a unique document identifier is genuinely useful.
  • Avoid using IDs for every reusable visual style.
  • Keep ID values unique within the document.
  • Remember that element selectors do not use a prefix.
  • Remember that class selectors begin with a dot.
  • Remember that ID selectors begin with a hash symbol.
  • Remember that the universal selector uses an asterisk.
  • Use commas to group independent selectors.
  • Do not confuse selector grouping with descendant selection.
  • Write h1, h2 to target both headings.
  • Write h1 h2 only when targeting h2 elements inside h1 elements.
  • Use descendant selectors when any nesting depth is acceptable.
  • Use child selectors when the direct parent-child relationship matters.
  • Use adjacent sibling selectors for the immediate next sibling.
  • Use general sibling selectors for matching later siblings.
  • Use attribute selectors when the attribute itself represents the styling condition.
  • Use exact attribute matching when exact values matter.
  • Use prefix, suffix, and substring attribute selectors carefully.
  • Use pseudo-classes for states and structural conditions.
  • Provide visible focus styles for keyboard users.
  • Do not remove focus indicators without providing an accessible replacement.
  • Do not depend only on hover for essential information.
  • Use :checked for appropriate form-control states.
  • Use :disabled for disabled form controls.
  • Use structural pseudo-classes when they accurately represent the document structure.
  • Use pseudo-elements for decorative or partial styling.
  • Use ::before and ::after carefully.
  • Remember that ::before and ::after commonly require the content property to generate content.
  • Do not place essential information only in generated decorative content.
  • Keep selector chains short when possible.
  • Avoid deeply nested selectors.
  • Avoid unnecessary specificity.
  • Prefer reusable classes over highly specific structural selectors for components.
  • Do not add selectors only to increase specificity without understanding the conflict.
  • Understand why a rule loses before increasing selector strength.
  • Use browser developer tools to inspect matched rules.
  • Check whether a selector is actually matching the intended element.
  • Check whether another rule overrides the declaration.
  • Check inherited values when debugging text styles.
  • Check specificity when multiple rules set the same property.
  • Check source order when competing declarations otherwise have equal priority.
  • Remember that specificity is only one part of the cascade.
  • Learn the difference between selector matching and cascade resolution.
  • A selector first determines whether a rule applies.
  • The cascade then determines which competing declaration wins.
  • Keep naming conventions consistent.
  • Use a project-wide class naming strategy when working on large applications.
  • Avoid class names that are difficult to understand.
  • Avoid random abbreviations unless the team understands them.
  • Avoid styling elements through unstable generated class names.
  • Avoid depending excessively on exact DOM depth.
  • Use component-level classes for reusable UI.
  • Use state classes when an application explicitly manages state.
  • Use data attributes when they represent meaningful data or state.
  • Do not use attribute selectors as a replacement for every class.
  • Balance precision with readability.
  • Test selectors after HTML structure changes.
  • Review selectors during component refactoring.
  • Remove unused selectors when safe.
  • Do not leave old selectors targeting elements that no longer exist.
  • Use code search before renaming widely used classes.
  • Keep related selectors together.
  • Format long grouped selectors across multiple lines.
  • Use consistent spacing around combinators.
  • Use comments only when selector intent is not obvious.
  • Avoid comments that merely repeat the selector.
  • Test interaction pseudo-classes with a mouse.
  • Test focus states with a keyboard.
  • Test form state selectors with real controls.
  • Test responsive interfaces on touch devices.
  • Practice element selectors.
  • Practice reusable class selectors.
  • Practice unique ID selectors.
  • Practice grouping selectors.
  • Practice descendant and child selectors.
  • Practice sibling selectors.
  • Practice attribute selectors.
  • Practice pseudo-classes.
  • Practice pseudo-elements.
  • Practice reading selectors from right to left conceptually when analyzing complex matching.
  • Build small examples before using complex selectors in a large project.
  • Use selector precision intentionally.
  • Keep CSS predictable.
  • Keep CSS maintainable.
  • Learn selectors thoroughly before moving to advanced styling topics.
Good Selectors Are Precise and Maintainable

A good selector targets the intended elements without being unnecessarily broad, complex, or difficult to override.

Frequently Asked Questions

What is a CSS selector?

A CSS selector is a pattern used to identify HTML elements that should receive CSS declarations.

What is an element selector?

An element selector targets HTML elements by their tag name, such as p, h1, or button.

What is a class selector?

A class selector targets elements containing a specific class and begins with a dot, such as .card.

Can the same class be used on multiple elements?

Yes. Classes are designed to be reusable across multiple elements.

What is an ID selector?

An ID selector targets an element by its id value and begins with a hash symbol, such as #header.

Can the same ID be used multiple times?

An ID value should be unique within an HTML document.

What is the difference between a class and an ID?

A class is reusable across multiple elements, while an ID should uniquely identify one element in the document.

What does the universal selector do?

The * selector can match all elements.

How do I group multiple selectors?

Separate independent selectors with commas, such as h1, h2, h3.

What is a descendant selector?

A descendant selector uses a space to target matching elements anywhere inside another element.

What is a child selector?

A child selector uses > to target only direct children.

What is the difference between div p and div > p?

div p matches paragraph descendants at any depth inside a div, while div > p matches only paragraphs that are direct children of the div.

What does the + selector mean?

The adjacent sibling combinator targets the immediate next matching sibling.

What does the ~ selector mean?

The general sibling combinator targets matching siblings that appear later after another element.

What is an attribute selector?

An attribute selector targets elements according to the presence or value of an HTML attribute.

How do I target only email inputs?

You can use input[type="email"].

What is a pseudo-class?

A pseudo-class targets an element based on a state, condition, or structural position, such as :hover or :first-child.

What is a pseudo-element?

A pseudo-element targets a specific part of an element or a generated box, such as ::first-letter or ::before.

What is the difference between :hover and ::before?

:hover is a pseudo-class representing an interaction state, while ::before is a pseudo-element that creates a styleable generated box before the element content.

Can selectors be combined?

Yes. Selectors can be combined to target elements more precisely.

What is specificity?

Specificity is one part of the CSS cascade used to compare competing selectors when declarations apply to the same element and property.

Which is generally more specific: class or element?

A class selector has greater specificity than an element selector.

Which is generally more specific: ID or class?

An ID selector has greater specificity than a class selector.

Does the most specific selector always win?

Not in every situation. Importance, origin, cascade layers, specificity, and source order can all affect the winning declaration.

Why is my selector not working?

Possible reasons include a spelling mistake, incorrect class or ID prefix, incorrect HTML structure, a selector that does not match, or another declaration winning in the cascade.

How can I debug selectors?

Use browser developer tools to inspect the element and review matched, overridden, and inherited CSS rules.

Should I use very long selectors?

Usually no. Shorter selectors are often easier to understand, reuse, and maintain.

What selector should beginners use most often?

Element selectors are useful for broad defaults, while class selectors are commonly used for reusable component styling.

What comes after CSS selectors?

The next lesson covers CSS colors and the different ways to define and apply colors.

Key Takeaways

  • CSS selectors identify which HTML elements should receive styles.
  • Selectors are written before declaration blocks.
  • Element selectors target elements by tag name.
  • Class selectors begin with a dot.
  • Classes can be reused on multiple elements.
  • ID selectors begin with a hash symbol.
  • ID values should be unique within a document.
  • The universal selector uses an asterisk.
  • The universal selector can match all elements.
  • Grouping selectors use commas.
  • Grouping allows multiple selectors to share declarations.
  • Combinators describe relationships between elements.
  • A space creates a descendant selector.
  • The descendant selector can match at any nesting depth.
  • The > symbol creates a child selector.
  • The child selector matches direct children only.
  • The + symbol creates an adjacent sibling selector.
  • The adjacent sibling selector targets the immediate next sibling.
  • The ~ symbol creates a general sibling selector.
  • The general sibling selector targets matching later siblings.
  • Attribute selectors use square brackets.
  • Attribute selectors can test attribute presence or values.
  • Pseudo-classes usually begin with a single colon.
  • Pseudo-classes target states and conditions.
  • :hover targets an element during pointer hover.
  • :focus targets an element that has focus.
  • :checked targets checked form controls.
  • Structural pseudo-classes target elements according to position.
  • Pseudo-elements normally use two colons.
  • Pseudo-elements can target parts of elements.
  • ::before and ::after create generated boxes.
  • Selectors can be combined for more precise targeting.
  • .card h2 targets h2 elements inside .card.
  • .card > h2 targets direct h2 children of .card.
  • button.primary targets button elements with the primary class.
  • Selector matching determines whether a CSS rule applies.
  • Specificity helps compare competing selectors.
  • Element selectors generally have lower specificity than class selectors.
  • Class selectors generally have lower specificity than ID selectors.
  • Specificity is only one part of the cascade.
  • Source order can matter when competing declarations otherwise have equal priority.
  • A valid declaration has no effect if its selector does not match.
  • Overly complex selectors are difficult to maintain.
  • Reusable classes are important for component styling.
  • Browser developer tools help debug selector problems.
  • Good selectors are precise, readable, and maintainable.
  • Selectors are the foundation of controlling CSS styles.

Summary

CSS selectors determine which HTML elements receive styling declarations.

Element selectors target HTML tags, class selectors target reusable class values, and ID selectors target unique identifiers.

The universal selector can match all elements, while grouping selectors allow multiple independent selectors to share the same declarations.

Combinators allow elements to be selected according to their relationships in the HTML structure.

The descendant selector targets nested elements at any depth, while the child selector targets direct children only.

Adjacent and general sibling selectors target elements according to their sibling relationships.

Attribute selectors target elements according to HTML attributes and their values.

Pseudo-classes target states and conditions such as hover, focus, checked, and structural positions.

Pseudo-elements target specific parts of elements or create styleable generated boxes.

Selectors can be combined to create precise targeting patterns.

When multiple declarations compete for the same property, specificity can help determine the winner as part of the larger CSS cascade.

Good selectors should be precise enough to target the correct elements while remaining simple enough to understand and maintain.

In the next lesson, you will learn CSS colors and discover the different ways to add color to text, backgrounds, borders, and other visual elements.