2 min read

Pseudo-classes and Pseudo-elements

Pseudo-classes and pseudo-elements are keywords added to selectors that specify a special state of the selected element(s) or style specific parts of an element.

1. Pseudo-classes

A pseudo-class is used to define a special state of an element. For example, it can be used to:

  • Style an element when a user mouses over it.
  • Style visited and unvisited links differently.
  • Style an element when it gets focus.

Syntax: selector:pseudo-class { property: value; }

Common Pseudo-classes

  • :hover: Selects elements when the mouse is over them.
  • :active: Selects elements while they are being activated (clicked).
  • :focus: Selects elements that have focus (clicked or tabbed into).
  • :visited: Selects visited links.
  • :first-child: Selects the first child of a parent.
  • :last-child: Selects the last child of a parent.
  • :nth-child(n): Selects the nth child of a parent.
  • :not(selector): Selects every element that is not the specified element/selector.
/* Change color on hover */
a:hover {
  color: red;
}

/* Select every even table row */
tr:nth-child(even) {
  background-color: <a href='/?search=%23f2f2f2' class='obsidian-tag'>#f2f2f2</a>;
}

/* Select input fields when focused */
input:focus {
  border: 2px solid blue;
}

2. Pseudo-elements

A pseudo-element is used to style specified parts of an element. For example, it can be used to:

  • Style the first letter, or line, of an element.
  • Insert content before, or after, the content of an element.

Syntax: selector::pseudo-element { property: value; }

Common Pseudo-elements

  • ::before: Inserts content before the content of an element.
  • ::after: Inserts content after the content of an element.
  • ::first-letter: Selects the first letter of a text block.
  • ::first-line: Selects the first line of a text block.
  • ::selection: Selects the portion of an element that is selected by a user.
/* Add an icon before every link */
a::before {
  content: "🔗 ";
}

/* Style the first letter of a paragraph */
p::first-letter {
  font-size: 200%;
  color: red;
}

The content Property

The content property is required for ::before and ::after to work. It specifies what is inserted. It can be an empty string "" if you just want to create a visual shape.

3. Single Colon vs. Double Colon

  • Single Colon (:): Used for Pseudo-classes (CSS1/CSS2 syntax).
  • Double Colon (::): Used for Pseudo-elements (CSS3 syntax).

This distinction was introduced in CSS3 to distinguish between classes (states) and elements (parts). However, for backward compatibility, browsers accept single colons for legacy pseudo-elements like :before, :after, :first-line, and :first-letter.

Best Practice: Use double colons (::) for pseudo-elements and single colons (:) for pseudo-classes.

programming/css/css programming/css/selectors programming/css/css3