Sobes.tech
Junior

What are pseudo-classes in CSS?

sobes.tech AI

Answer from AI

CSS pseudo-classes are keywords added to selectors to specify a special state of an element. They allow styling elements based on their interaction with the user, their position in the document structure, or other characteristics that cannot be expressed with standard selectors.

Examples of pseudo-classes:

  • User states:

    • :hover - the element that the mouse cursor is over.
    • :active - the element that is being activated (e.g., mouse button pressed).
    • :focus - the element that is in focus for input (e.g., a text field).
    • :visited - a link that the user has already visited.
    • :link - a link that the user has not visited yet.
  • Position in the structure:

    • :first-child - the first child element of its parent.
    • :last-child - the last child element of its parent.
    • :nth-child(n) - the n-th child element of its parent.
    • :first-of-type - the first element of its type among the children.
    • :last-of-type - the last element of its type among the children.
  • Others:

    • :empty - an element that contains no child elements or text.
    • :not(selector) - elements that do not match the specified selector.

Syntax:

selector:pseudo-class {
  property: value;
}

Example usage:

/* Change text color on hover over a paragraph */
p:hover {
  color: blue;
}

/* Style for the first list item */
li:first-child {
  font-weight: bold;
}

Pseudo-classes extend the capabilities of selectors, allowing for more dynamic and interactive interfaces without using JavaScript for simple style changes.