Pseudo-classes apply styles to elements based on their state or position in the document tree.
:Hover
The :hover
pseudo-class applies styles when the user hovers over an element.
a:hover { color: red; }
:Focus
The :focus
pseudo-class applies styles when an element receives focus, such as when a user clicks on an input field.
input:focus { border-color: blue; }
:Nth-child(n)
The :nth-child(n)
pseudo-class applies styles to the nth child of a parent element
li:nth-child(odd) { background-color: lightgrey; }
:First-child
The :first-child
pseudo-class applies styles to the first child of a parent element.
p:first-child { font-weight: bold; }
CSS Pseudo-classes Example Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Pseudo-classes Example</title> <style> a:hover { color: red; } input:focus { border-color: blue; } li:nth-child(odd) { background-color: lightgrey; } p:first-child { font-weight: bold; } </style> </head> <body> <a href="#">Hover over this link</a> <br><br> <input type="text" placeholder="Focus on me"> <br><br> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <p>This is the first paragraph.</p> <p>This is another paragraph.</p> </body> </html>