Pseudo Classes in CSS
? Pseudo-classes in CSS
Pseudo-classes let you style elements based on their state or position without needing extra classes or JavaScript.
They use a colon : followed by the pseudo-class name.
Common Pseudo-classes
| Pseudo-class | Description | Example |
|---|---|---|
:hover | When the mouse pointer is over an element | a:hover { color: red; } |
:focus | When an element is focused (e.g., input focus) | input:focus { border-color: blue; } |
:active | When an element is being activated (clicked) | button:active { background: gray; } |
:visited | For links that have been visited | a:visited { color: purple; } |
:first-child | First child element of its parent | p:first-child { font-weight: bold; } |
:last-child | Last child element of its parent | li:last-child { margin-bottom: 0; } |
:nth-child(n) | The nth child of its parent | li:nth-child(2) { color: green; } |
:not(selector) | Negates a selector | div:not(.highlight) { opacity: 0.5; } |
Example Usage
/* Change link color on hover */a:hover { color: orange;}/* Highlight focused input */input:focus { outline: 2px solid blue;}/* Style every even list item */li:nth-child(even) { background-color: #f0f0f0;}/* Style all paragraphs except those with class 'special' */p:not(.special) { color: gray;}Why Use Pseudo-classes?
Style interactive states like hover, focus, active.
Target elements by position without extra markup.
Create more dynamic, responsive designs with pure CSS.
Want me to cover pseudo-elements like ::before and ::after next?