CSS Pseudo-classes and Pseudo-elements

Introduction CSS pseudo-classes and pseudo-elements allow developers to apply styles to specific states of elements or parts of elements without modifying the HTML structure. They enhance interactivity and design flexibility. 1. CSS Pseudo-classes Pseudo-classes target elements based on user interactions, positions, or other conditions. Common Pseudo-classes 2. CSS Pseudo-elements Pseudo-elements style specific parts of an […]

  • Post author:
  • Post category: CSS
  • Reading time: 7 mins read
  • Post last modified: April 3, 2025

Introduction

CSS pseudo-classes and pseudo-elements allow developers to apply styles to specific states of elements or parts of elements without modifying the HTML structure. They enhance interactivity and design flexibility.

1. CSS Pseudo-classes

Pseudo-classes target elements based on user interactions, positions, or other conditions.

Common Pseudo-classes

  1. :hover – Styles an element when hovered. button:hover { background-color: blue; }
  2. :focus – Applies styles when an element is focused. input:focus { border: 2px solid green; }
  3. :nth-child(n) – Targets the nth child of a parent. tr:nth-child(even) { background-color: lightgray; }
  4. :first-child & :last-child – Targets the first and last child. p:first-child { font-weight: bold; }
  5. :not(selector) – Excludes specific elements. div:not(.no-style) { background-color: yellow; }

2. CSS Pseudo-elements

Pseudo-elements style specific parts of an element.

Common Pseudo-elements

  1. ::before & ::after – Inserts content before or after an element. h1::before { content: "🔥 "; }
  2. ::first-letter – Styles the first letter. p::first-letter { font-size: 2em; color: red; }
  3. ::first-line – Styles the first line. p::first-line { font-weight: bold; }
  4. ::selection – Styles selected text. ::selection { background-color: yellow; }

3. Combining Pseudo-classes and Pseudo-elements

You can mix both for more advanced styles.

Example:

p:first-child::first-letter {
    font-size: 2em;
    color: blue;
}
CSS

Conclusion

Pseudo-classes and pseudo-elements enhance CSS styling by targeting elements dynamically. Using them efficiently improves interactivity and aesthetics.

Leave a Reply