Pseudo-classes in CSS allow styling elements based on their state or position in the DOM tree. The differences
between :first-child
, :first-of-type
, and :first
are as follows:
:first-child
selects the first child element of a parent.- Example:
p:first-child
selects the first paragraph among the parent's children.
- Example:
:first-of-type
selects the first element of a given type from a parent.- Example:
p:first-of-type
selects the first paragraph of a given type among the parent's children.
- Example:
/* Examples */ p:first-child { color: red; /* Changes the color of the first paragraph among siblings */ } p:first-of-type { color: blue; /* Changes the color of the first paragraph of a given type among siblings */ }