CSS ยท Chapter 29 of 44
CSS Pseudo-Classes
Pseudo-classes select elements based on a special state, such as :hover, :first-child, :last-child, :nth-child(), and :not().
They let you style elements dynamically without adding extra classes or JavaScript.
Syntax
selector:pseudo-class { }State-based pseudo-classes
:hover, :focus, and :checked style elements based on user interaction or form state.
Structural pseudo-classes
:first-child, :last-child, and :nth-child(n) select elements based on their position among siblings, without needing extra markup.
Example 1 (css)
li:nth-child(odd) {
background: #eee;
}
input:focus {
border-color: blue;
}Output
Odd list items get a light gray background; focused inputs get a blue borderStructural and state pseudo-classes both style elements without extra classes.
Key points
- :hover styles elements on mouse-over.
- :nth-child(n) selects elements by sibling position.
- :not() excludes elements matching a selector.
- Pseudo-classes avoid the need for extra HTML classes or JavaScript.
๐ก Note: :nth-child(2n) selects every second element, useful for striping rows.
