Skip to main content

Command Palette

Search for a command to run...

CSS Selectors: A Quick Reference

Published
2 min read

CSS selectors are the mechanism used to target HTML elements for styling. They act as the link between your markup (HTML) and your design rules (CSS). Without selectors, styles cannot be applied to specific parts of a webpage.

Definition

CSS selectors are the binding mechanism between the Document Object Model (DOM) and the render tree. Browsers parse HTML into a DOM tree and CSS into a CSSOM (CSS Object Model). Selectors are the query engine used to match style rules to DOM nodes during the paint process.

Types of CSS Selectors

  1. Element Selector

    The element selector targets all instances of a specific HTML tag. It is useful for defining default styles across a document.

    • Syntax: Use the tag name directly.

    • Example: Targeting all <p> tags.

        p {
          font-size: 16px;
          line-height: 1.5;
        }
      
  2. Class Selector

    The class selector targets elements with a specific class attribute. Classes are reusable and can be applied to multiple elements on a single page.

    • Syntax: Use a dot (.) followed by the class name.

    • Example: Targeting any element with class="card".

        .card {
          border: 1px solid #ccc;
          padding: 20px;
        }
      
  3. ID Selector

    The ID selector targets a single element with a specific id attribute. An ID must be unique within a page, meaning it should only be used once per document.

    • Syntax: Use a hash (#) followed by the ID name.

    • Example: Targeting an element with id="header".

        #header {
          background-color: #333;
          color: white;
        }
      
  4. Group Selector

    Group selectors allow you to apply the same styles to multiple selectors at once. This reduces code redundancy.

    • Syntax: Separate selectors with a comma (,).

    • Example: Applying the same font family to h1, h2, and h3.

        h1, h2, h3 {
          font-family: Arial, sans-serif;
          font-weight: bold;
        }
      
  5. Descendant Selectors

    Descendant selectors target an element only if it is nested inside another specific element. This allows for context-specific styling.

    • Syntax: Separate selectors with a space.

    • Example: Targeting <a> tags that are inside a nav element.

        nav a {
          text-decoration: none;
          color: blue;
        }
      

Selector Priority

When multiple rules apply to the same element, CSS uses a hierarchy called "specificity" to decide which style wins.

The basic order of priority (from highest to lowest) is:

  1. ID Selector (#id) – Highest priority.

  2. Class Selector (.class) – Medium priority.

  3. Element Selector (tag) – Lowest priority.