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
:hover– Styles an element when hovered.button:hover { background-color: blue; }:focus– Applies styles when an element is focused.input:focus { border: 2px solid green; }:nth-child(n)– Targets the nth child of a parent.tr:nth-child(even) { background-color: lightgray; }:first-child&:last-child– Targets the first and last child.p:first-child { font-weight: bold; }: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
::before&::after– Inserts content before or after an element.h1::before { content: "🔥 "; }::first-letter– Styles the first letter.p::first-letter { font-size: 2em; color: red; }::first-line– Styles the first line.p::first-line { font-weight: bold; }::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;
}CSSConclusion
Pseudo-classes and pseudo-elements enhance CSS styling by targeting elements dynamically. Using them efficiently improves interactivity and aesthetics.

