Account
Categories

Types of CSS Selectors


There are different types of CSS selectors which are listed below:

  1. Basic Selectors:

    Element Selector: Element Selector refers to selecting HTML elements directly by their tag name to apply styles.

    p { color: blue; }

    Class Selector: Class selectors apply styles to HTML elements using a period followed by the class name.

    .title { font-size: 20px; }

    ID Selector: ID Selectors style a unique HTML element using # and the ID name.

    #main { background-color: yellow; }
  2. Grouping Selector:

    Grouping Selector refers to applying the same styles to multiple HTML elements.

    h1, h2, p { color: red; }
  3. Combinator Selectors:
    • Descendant Selector: Descendant Selector refers to selecting elements that are nested within a specific parent element.
      div p { font-size: 16px; }
    • Child Selector (>): Child Selector refers to selecting only the direct children of a specific element.
      ul > li { list-style: square; }
    • Adjacent Sibling Selector (+): The Adjacent Sibling Selector is used to select an HTML element that directly follows another specified element.
      h1 + p { margin-top: 10px; }
    • General Sibling Selector (~): General Sibling Selector refers to selecting all siblings that follow a specific element.
      h1 ~ p { color: gray; }
  4. Attribute Selectors:

    Attribute Selector refers to selecting HTML elements based on the presence or value of their attributes.

    input[type="text"] { border: 1px solid black; }
  5. Pseudo-classes:

    Pseudo-class refers to styling elements based on their state or position in the document structure.

    a:hover { color: green; }
    li:first-child { font-weight: bold; }
    p:nth-child(2) { color: orange; }
  6. Pseudo-elements:

    Pseudo-element refers to styling specific parts of HTML elements like the first letter or content before/after.

    p::first-letter { font-size: 150%; }
    p::before { content: "before"; }
    p::after { content: "after"; }
  7. Universal Selector (*):

    Universal Selector refers to selecting all HTML elements on the page.

    * { margin: 0; padding: 0; }
  8. Negation Pseudo-class (:not()):

    Negation Pseudo-class refers to selecting all elements except the one(s) specified.

    p:not(.intro) { color: gray; }
  9. :is() and :where() Selectors (CSS3+):

    :is() and :where() selectors refer to simplifying multiple selectors under one rule.

    :is(h1, h2, h3) { font-weight: bold; }
    :where(article, section) { padding: 10px; }
  10. Nesting Selector (Upcoming / SCSS-like via &):

    Nesting Selector is a technique used in preprocessors like SCSS to group styles with the parent reference (&).

    .btn { color: blue; 
      &:hover { color: red; } 
    }

    Note: Nesting is not supported natively in CSS until CSS Nesting (Level 4); SCSS allows this as a feature.