2 min read

CSS Selectors

CSS selectors are used to "find" (or select) the HTML elements you want to style.

1. Basic Selectors

  • *Universal Selector (``)**: Selects all elements on the page.
    * {
      margin: 0;
      padding: 0;
    }
  • Type Selector (Element Selector): Selects all elements of a given type name.
    p {
      color: red;
    }
  • Class Selector (.): Selects all elements with a specific class attribute.
    .intro {
      font-weight: bold;
    }
  • ID Selector (#): Selects a single element with a specific id attribute.
    <a href='/?search=%23header' class='obsidian-tag'>#header</a> {
      background-color: grey;
    }
  • Grouping Selector (,): Selects all the matching elements.
    h1, h2, p {
      text-align: center;
    }

2. Combinators

Combinators explain the relationship between the selectors.

  • Descendant Selector (space): Matches all elements that are descendants of a specified element.
    div p {
      background-color: yellow;
    }
  • Child Selector (>): Matches all elements that are direct children of a specified element.
    div > p {
      background-color: yellow;
    }
  • Adjacent Sibling Selector (+): Matches an element that is immediately preceded by a specific element.
    div + p {
      background-color: yellow;
    }
  • General Sibling Selector (~): Matches all elements that are preceded by a specific element.
    div ~ p {
      background-color: yellow;
    }

3. Attribute Selectors

Select elements based on the presence or value of a given attribute.

  • [attribute]: Elements with the attribute.
  • [attribute="value"]: Elements with the attribute having the exact value.
  • [attribute^="value"]: Elements whose attribute value begins with "value".
  • [attribute$="value"]: Elements whose attribute value ends with "value".
  • [attribute*="value"]: Elements whose attribute value contains the substring "value".

programming/css/css programming/html/html