8. What are pseudo-classes in CSS and what are their uses?

Pseudo-classes are special selectors that define a specific state of elements, such as user interactions. Some of the most commonly used pseudo-classes are:

  • :hover: styles an element when the user hovers over it with the cursor.
  • :active: styles an element at the moment it is clicked.
  • :focus: styles an element when it is in focus (e.g., a form field that the user has clicked on).
  • :nth-child(n): styles the nth element among its siblings.
  • :first-child: styles the first element among its siblings.
  • :last-child: styles the last element among its siblings.
/* Examples */ button:hover { background-color: yellow; /* Changes the button's background color to yellow on hover */ } button:active { background-color: green; /* Changes the button's background color to green on click */ } input:focus { border-color: blue; /* Changes the border color of the text field to blue when focused */ } li:nth-child(2) { color: red; /* Changes the color of the second list item to red */ } p:first-child { font-weight: bold; /* Changes the font weight of the first paragraph to bold */ }
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.