Skip to content

CSS Pseudo-Classes and Pseudo-Elements

Pseudo-Classes

Pseudo-classes define the special state of an element. They are used to apply styles based on the state or the position of an element.

Common Pseudo-Classes:
  1. :hover: Applies when the user hovers over an element.
button:hover {
background-color: blue;
}
  1. :focus: Applies when an element is focused (e.g., an input field)
input:focus {
border-color: green;
}
  1. :nth-child(n): Matches elements based on their position in a parent (1-based index).
li:nth-child(2) {
color: red;
}
  1. :first-child / :last-child: Targets the first or last child element.
p:first-child {
font-weight: bold;
}
  1. :disabled: Targets disabled form elements.
input:disabled {
background-color: lightgray;
}

Pseudo-Elements

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

Common Pseudo-Elements:
  1. ::before: Inserts content before an element’s actual content.
h1::before {
content: "Chapter: ";
font-weight: bold;
}
  1. ::after: Inserts content after an element’s actual content.
h1::after {
content: " - End";
font-style: italic;
}
  1. ::first-letter: Styles the first letter of a block of text.
p::first-letter {
font-size: 2em;
color: red;
}
  1. ::first-line: Styles the first line of a block of text.
p::first-line {
font-weight: bold;
}
  1. ::selection: Styles the portion of text selected by the user.
::selection {
background-color: lightblue;
}