CSS Selectors

Learn how CSS selects HTML elements and styles them precisely.

What are CSS Selectors?

CSS Selectors are patterns used to select HTML elements that you want to style. They tell the browser “Which element should receive this CSS?”

  • Select elements by tag name
  • Select elements by class or id
  • Select elements based on position or state
  • Apply styles efficiently and cleanly

Real-Life Example: Like calling a specific student by name, roll number, or uniform color in a classroom.

Basic CSS Selectors

  • Element Selector
  • Class Selector
  • ID Selector
  • Universal Selector

Element Selector

The element selector selects all HTML elements of a specific type.

Styling All Paragraphs


p {
    color: #374151;
    font-size: 16px;
    line-height: 1.6;
}

Explanation: This applies the same style to every <p> tag on the page.

Class Selector

A class selector selects elements with a specific class name. Classes can be reused multiple times.

Class Selector Example


.highlight {
    background-color: #e0f2fe;
    padding: 10px;
    border-left: 4px solid #2563eb;
}

Pro Tip: Use classes for reusable designs like buttons, cards, and alerts.

ID Selector

An ID selector selects a single unique element. IDs should never be repeated.

ID Selector Example


#main-title {
    font-size: 32px;
    color: #1e40af;
    text-align: center;
}

Important: Use IDs for unique elements like headers or main containers.

Attribute Selectors

Attribute selectors target elements based on their attributes.

Attribute Selector Example


input[type="text"] {
    border: 2px solid #2563eb;
    padding: 8px;
}

Pseudo-classes

Pseudo-classes style elements based on user actions or states.

  • :hover
  • :focus
  • :first-child
  • :last-child

Hover Example


a:hover {
    color: #2563eb;
    text-decoration: underline;
}

Best Practices for CSS Selectors

  • Prefer class selectors over IDs
  • Avoid overly complex selectors
  • Keep selectors readable
  • Write scalable CSS

Pro Tip: Clean selectors = clean and maintainable CSS.