Isaac.

Introduction to CSS Selectors

Cascading Style Sheets (CSS) selectors are patterns that tell the browser which HTML elements to apply a given style to. They're the foundation of CSS, allowing you to target specific elements on a webpage for styling.

Basic Selectors

  • Type Selector:
    p { color: blue; }
  • Class Selector:
    .highlight { background-color: yellow; }

Combinator Selectors

Combinators are used to combine other selectors in meaningful ways.

  • div p { color: green; }
  • ul > li { list-style-type: square; }

Attribute Selectors

  • a[target] { color: purple; }
  • img[src$=".png"] { border: 2px solid red; }

Pseudo-classes

Pseudo-classes select elements based on their state or position.

  • :hover — Selects an element when the user hovers over it.
    button:hover { background-color: lightblue; }
  • :nth-child(2n) — Selects even-numbered list items.
    li:nth-child(2n) { color: red; }
  • :not(.active) — Excludes elements with a specific class.
    div:not(.active) { opacity: 0.5; }

Pseudo-elements

Pseudo-elements allow you to style specific parts of an element.

  • ::before — Inserts content before an element.
    p::before { content: "★ "; }
  • ::after — Inserts content after an element.
    p::after { content: " ✔"; }
  • ::first-letter — Styles the first letter of a block.
    p::first-letter { font-size: 2em; }

Pseudo-classes vs Pseudo-elements

AspectPseudo-classesPseudo-elements
DefinitionSelect elements based on state or position.Select parts of an element (not whole elements).
SyntaxSingle colon (:)Double colon (::)
Examples:hover, :nth-child::before, ::first-letter

By combining pseudo-classes and pseudo-elements, you can achieve highly specific and creative styling with minimal markup.