CSS Pseudo-class


In CSS, a Pseudo class is used to define an element's special state. It can be used in conjunction with a CSS selector to add a state-based effect to existing elements. For instance, changing the style of an element when the user hovers over it or clicks on a link. All of this is possible with CSS Pseudo Classes.

Syntax


There are many Pseudo classes in CSS, but the most common ones are as follows:

1. :hover Pseudo-class:

This pseudo-class is used to add a special effect to an element when we hover our mouse over it. The following example shows how your mouse's background color changes from yellow to orange when it enters the box area.

Example

Preview

2. :active Pseudo-class:

This pseudo-class is used to identify an element that will be activated when the user clicks on it. The following example shows how, when you click on the box, the background color changes for a brief moment.

Example

Preview

3. :focus Pseudo-class:

This pseudo-class is used to select the element on which the user is currently focused. It operates on form user input elements and is triggered when the user clicks on them. In the following example, the background color of the currently focused input field changes.

Example

Preview

4. :visited Pseudo-class:

This pseudo-class is used to select links that the user has already visited. The color of the link in the following example changes when it is visited.

Example

Preview

FAQs

The :nth-child() pseudo-class is used to select and style specific child elements of a parent element based on their position. It takes a single argument, which is a formula for selecting the desired child elements. For example, the selector :nth-child(odd) selects all odd-numbered child elements of a parent element.

The :first-child pseudo-class is used to select and style the first child element of a parent element. It is often used to style the first item in a list differently than the other items.

Pseudo-classes select and style a specific state or condition of an element, while pseudo-elements select and style a specific part of an element. Pseudo-classes are represented by a single colon, while pseudo-elements are represented by two colons.