Skip to main content

Pseudo-Class and Pseudo-Element Selectors

Introduction to Pseudo-Class and Pseudo-Element Selectors

Pseudo-class and pseudo-element selectors are an integral part of CSS, providing dynamic styling to various aspects of our documents. Unlike other CSS selectors, pseudo-class and pseudo-element selectors allow us to style elements based on their state, or the part of the element itself.

What are Pseudo-Class Selectors?

Pseudo-class selectors are used to select elements that are in a specific state. For example, a link that is being hovered over or a checkbox that is checked. Pseudo-classes are specified using a colon (:) followed by the pseudo-class name. Here are a few examples:

a:hover {
color: red;
}

input:checked {
background-color: blue;
}

In the first example, the :hover pseudo-class is used to change the color of a link when it is hovered over. In the second example, the :checked pseudo-class is used to change the background color of a checked input element.

What are Pseudo-Element Selectors?

Pseudo-element selectors, on the other hand, are used to select and style a part of an element. For example, you can select the first letter or line of a paragraph, before or after an element etc. Pseudo-elements are specified using two colons (::) followed by the pseudo-element name. Here's an example:

p::first-letter {
font-size: 2em;
color: green;
}

In this example, the ::first-letter pseudo-element is used to change the font size and color of the first letter of every paragraph.

Common Pseudo-Class Selectors

Here are some commonly used pseudo-class selectors:

  • :hover - Selects an element when it is being hovered over.

  • :focus - Selects an element when it has focus.

  • :active - Selects an element during the activation of the element.

  • :visited - Selects all links that the user has visited.

  • :checked - Selects every checked <input> element.

  • :first-child - Selects every element that is the first child of its parent.

Common Pseudo-Element Selectors

Here are some commonly used pseudo-element selectors:

  • ::before - Inserts something before the content of each selected element.

  • ::after - Inserts something after the content of each selected element.

  • ::first-letter - Selects the first letter of each selected element.

  • ::first-line - Selects the first line of each selected element.

Conclusion

Pseudo-class and pseudo-element selectors offer a powerful way to select and style elements based on their state or a part of them. They provide dynamic styling capabilities and can greatly enhance the user interaction and experience of a website. Remember to use a single colon for pseudo-classes and double colons for pseudo-elements. Happy styling!