CSS Tutorial

Pseudo-Elements

Pseudo-elements are CSS constructs that allow you to add content or styling to elements without altering the underlying HTML. They are particularly beneficial for enhancing the visual appeal or functionality of an element.

Key Concepts

  • Before: Adds content or styling before the first child element.
  • After: Adds content or styling after the last child element.
  • First-letter: Styles the first letter of the first child element.
  • First-line: Styles the first line of the first child element.

Example of Before Pseudo-Element

The following CSS code adds the text "Example" before the <h1> element:

h1::before {
  content: "Example ";
}

Enhancing Accessibility and Ease of Use

Pseudo-elements can also be used to improve accessibility and ease of use, such as:

  • Adding screen reader text to images using the content property:
img::before {
  content: "Description of the image";
}
  • Creating visually hidden elements using the display property:
.visually-hidden {
  display: none;
}

Tips for Effective Use

  • Use pseudo-elements sparingly to avoid cluttering your CSS code.
  • Use descriptive names for pseudo-element classes to enhance readability.
  • Consider accessibility needs when using pseudo-elements.