Episode 18 of 53

Pseudo Selectors in CSS

Learn about pseudo-classes and pseudo-elements for styling states and generated content.

Pseudo-selectors let you style elements based on their state or target specific parts of an element. There are two types: pseudo-classes and pseudo-elements.

Pseudo-Classes

Pseudo-classes target elements in a specific state. They use a single colon ::

/* When hovering over a button */
button:hover {
    background-color: #2980b9;
    transform: translateY(-1px);
}

/* When an input is focused */
input:focus {
    outline: 2px solid #3498db;
    border-color: #3498db;
}

/* Visited links */
a:visited { color: purple; }

/* Active (being clicked) */
button:active { transform: translateY(1px); }

Pseudo-Elements

Pseudo-elements target a specific part of an element. They use double colons :::

/* Style the first line of a paragraph */
p::first-line {
    font-weight: bold;
    font-size: 1.1rem;
}

/* Style the first letter */
p::first-letter {
    font-size: 2rem;
    float: left;
    margin-right: 0.25rem;
}

/* Add content before/after an element */
.required::after {
    content: " *";
    color: red;
}

Common Pseudo-Classes

  • :hover — mouse is over the element
  • :focus — element has keyboard focus
  • :active — element is being activated (clicked)
  • :first-child, :last-child — position-based
  • :nth-child() — pattern-based selection