CSS Pseudo-classes and Pseudo-elements

CSS pseudo-classes and pseudo-elements are special types of selectors that can be used to target elements in specific states or to insert content into the document.

Pseudo-classes

Pseudo-classes are used to target elements in specific states, such as when the element is focused, hovered over, or selected.

  • :focus: This pseudo-class is used to target elements that are focused.
  • :hover: This pseudo-class is used to target elements that are hovered over.
  • :active: This pseudo-class is used to target elements that are clicked.
  • :checked: This pseudo-class is used to target elements that are checked.
  • :disabled: This pseudo-class is used to target elements that are disabled.

Pseudo-elements

Pseudo-elements are used to insert content into the document, such as the first letter of an element, the first line of an element, or the before and after content of an element.

  • ::first-letter: This pseudo-element is used to insert the first letter of an element.
  • ::first-line: This pseudo-element is used to insert the first line of an element.
  • ::before: This pseudo-element is used to insert content before an element.
  • ::after: This pseudo-element is used to insert content after an element.

Example

<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo-classes and Pseudo-elements Demo</title>
<style>
a:hover {
  color: red;
}

.element::before {
  content: "This is before the element content.";
}

.element::after {
  content: "This is after the element content.";
}
</style>
</head>
<body>
<a href="#">This is a link.</a>
<p class="element">This is the element content.</p>
</body>
</html>

Task

Make the button Submit change the background color to #007BFF and the color to #fff. Insert empty content, with display blockheight of 3px, and background color #007BFF after section h2. Run the code and experiment with the code to get used to it.

Conclusion

CSS pseudo-classes and pseudo-elements are a powerful tool for targeting elements in specific states and for inserting content into the document. By understanding how pseudo-classes and pseudo-elements work, you can create web pages that are more dynamic and interactive.

Here are some tips for using pseudo-classes and pseudo-elements:

  • Use pseudo-classes to target elements in specific states, such as when the element is focused, hovered over, or selected.
  • Use pseudo-elements to insert content into the document, such as the first letter of an element, the first line of an element, or the before and after content of an element.
  • Use pseudo-classes and pseudo-elements together to create more complex and dynamic effects.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT