D DevBrainBox

CSS Pseudo Classes

CSS

What is a Pseudo-class?

  • A CSS pseudo-class is a keyword added to a selector that targets elements in a specific state.
  • It starts with a colon (:).

Example:

:hover, :first-child

Common CSS Pseudo-classes

1. :hover

Styles an element when the mouse hovers over it.

button:hover {
  background-color: blue;
}

2. :active

Styles an element when it’s being clicked.

a:active {
  color: red;
}

3. :focus

Styles an element when it’s selected or focused (like an input field).

input:focus {
  border-color: green;
}

4. :first-child

Selects the first child of a parent.

li:first-child {
  font-weight: bold;
}

5. :last-child

Selects the last child.

p:last-child {
  color: gray;
}

6. :nth-child(n)

Selects the n-th element (e.g., every 2nd row).

tr:nth-child(2n) {
  background: #f0f0f0;
}

7. :checked

Targets a checked checkbox or radio button.

input:checked {
  outline: 2px solid green;
}

8. :disabled / :enabled

Styles form elements based on whether they’re disabled or enabled.

button:disabled {
  opacity: 0.5;
}

9. :not(selector)

Selects everything except the specified selector.

div:not(.active) {
  background: lightgray;
}

Example

input:focus {
  border: 2px solid #3498db;
}

li:nth-child(odd) {
  background-color: #fafafa;
}

a:hover {
  text-decoration: underline;
}
Pseudo-classWhat it targets
:hoverWhen user hovers with mouse
:activeWhen element is being clicked
:focusWhen an input is focused
:first-childFirst child of a parent
:nth-child(n)Specific child based on index
:checkedChecked input elements
:disabledDisabled form controls
:not()Excludes certain selectors

On this page