Lesson 3.9: Pseudo-classes & Pseudo-elements
Introduction
CSS pseudo-classes and pseudo-elements allow developers to style elements based on states, positions, or specific parts of content without adding extra HTML. They help create advanced styling effects efficiently.
1. Pseudo-classes
A pseudo-class defines the special state of an element. It is written using a colon : followed by the pseudo-class name.
Common Pseudo-classes:
-
:hover– Styles an element when the user hovers over it. -
:active– Styles an element when it is being clicked. -
:focus– Styles an element when it is focused (e.g., input field). -
:nth-child(n)– Selects the nth child of a parent. -
:first-child/:last-child– Selects the first or last child of an element.
Example:
2. Pseudo-elements
A pseudo-element styles specific parts of an element’s content. It is written with double colons :: (though some browsers allow a single colon).
Common Pseudo-elements:
-
::before– Inserts content before an element. -
::after– Inserts content after an element. -
::first-letter– Styles the first letter of a text. -
::first-line– Styles the first line of a text. -
::selection– Styles the selected text (when highlighted).
Example:
3. Difference between Pseudo-classes and Pseudo-elements
| Feature | Pseudo-class | Pseudo-element |
|---|---|---|
| Symbol | : |
:: |
| Purpose | Defines a state of an element | Styles a part of an element |
| Example | :hover, :focus |
::before, ::first-letter |
✅ Summary:
-
Pseudo-classes style elements based on state or position.
-
Pseudo-elements style specific parts of elements.
-
They are powerful tools for enhancing user experience and visual design.
