What is a pseudo-class? What pseudo-classes do you know?
A pseudo-class is a special selector that describes the state of an element, not the element itself. It triggers at the moment of a certain event or at a certain position of the element in the structure, without adding classes to HTML.
Example:
css
a:hover {
color: red;
}hover, a pseudo-class that applies the moment the cursor hovers over the element.
Groups of pseudo-classes and examples
1) User states
| Pseudo-class | When it triggers |
|---|---|
:hover | on cursor hover |
:active | on click/press |
:focus | on element focus (keyboard or cursor) |
:visited | a visited link |
:link | a link that hasn't been clicked yet |
2) Position in the tree (structural)
| Pseudo-class | Description |
|---|---|
:first-child | the first child in the parent |
:last-child | the last child |
:nth-child(n) | selection by number |
:nth-of-type(n) | the number among elements of a specific type |
:first-of-type, :last-of-type | the first/last element of a given type |
3) Form states
| Pseudo-class | Description |
|---|---|
:checked | a checked checkbox or radio button |
:disabled | a disabled form element |
:enabled | an available element |
:required, :optional | required/optional fields |
:valid, :invalid | passes/fails validation |
4) Other useful pseudo-classes
| Pseudo-class | Description |
|---|---|
:not(selector) | excludes a selector |
:root | the root element (html) |
:empty | an element with no content |
:target | the element referenced by #hash in the URL |
Summary
Pseudo-classes let you style an element based on its state or position without changing the HTML code. This makes CSS more flexible and dynamic.
If you'd like, I can cover pseudo-elements in the next question and show how they differ from pseudo-classes.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.