Cover Image for CSS pseudo-classes
118 views

CSS pseudo-classes

CSS pseudo-classes are special selectors used to target and style elements based on their state or position within the document tree. They start with a single colon : notation and allow you to apply styles to elements that are not based solely on their tag name, class, or ID.

Here are some commonly used CSS pseudo-classes:

  1. :hover: Selects an element when it is being hovered over by the mouse pointer.
  2. :active: Selects an element when it is being activated or clicked (e.g., when a button is pressed).
  3. :focus: Selects an element when it gains focus (e.g., when a form element like an input field is clicked or tabbed into).
  4. :visited: Selects a link that has been visited by the user.
  5. :first-child: Selects the first child element of its parent.
  6. :last-child: Selects the last child element of its parent.
  7. :nth-child(n): Selects the nth child element of its parent, where “n” is a number, keyword, or formula.
  8. :nth-of-type(n): Selects the nth element of a particular type (e.g., <p>, <div>) of its parent.
  9. :nth-last-child(n): Selects the nth child element of its parent, counting from the last child.
  10. :nth-last-of-type(n): Selects the nth element of a particular type of its parent, counting from the last element.
  11. :not(selector): Selects elements that do not match the specified selector.

Example:

/* Style links when hovered */
a:hover {
  color: red;
  text-decoration: underline;
}

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

/* Style odd rows of a table */
tr:nth-child(odd) {
  background-color: lightgray;
}

In the above examples, the first CSS rule applies styles to anchor (<a>) elements when they are hovered over. The second rule styles input fields (<input>) when they gain focus. The third rule styles odd rows of a table by using the :nth-child pseudo-class.

CSS pseudo-classes offer a powerful way to apply styles dynamically based on user interactions or the structure of the document. They enhance the interactivity and visual appeal of a webpage and help create more engaging and user-friendly designs.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS