Pseudo-classes and Pseudo-elements
A pseudo-class styles an element in a certain state. It starts with one colon.
Pseudo-classes let you style things that HTML can't mark up: the moment the mouse hovers over a button, the first item of a list, every second table row, or a form field with an invalid value. They make pages feel responsive and alive without any JavaScript.
:hover- the mouse is over it:focus/:focus-visible- it is selected with the keyboard:active- it is being pressed:first-child,:last-child,:nth-child(2n)- its position among its siblings:checked,:disabled,:invalid- form states
Example
<!DOCTYPE html>
<html>
<head>
<style>
.btn { background: #2563eb; color: #fff; border: 0; padding: 10px 18px; border-radius: 8px; }
.btn:hover { background: #1d4ed8; }
.btn:active { transform: scale(0.97); }
.btn:focus-visible { outline: 3px solid #f59e0b; }
tr:nth-child(even) { background: #f1f5f9; }
input:invalid { border-color: red; }
</style>
</head>
<body>
<button class="btn">Hover and press me</button>
<table>
<tr><td>Pen</td><td>₹20</td></tr>
<tr><td>Book</td><td>₹150</td></tr>
<tr><td>Bag</td><td>₹900</td></tr>
<tr><td>Lamp</td><td>₹600</td></tr>
</table>
<input type="email" placeholder="Type a wrong email">
</body>
</html>▶ Try it yourselfPseudo-elements
A pseudo-element styles a part of an element, or adds decoration. It starts with two colons.
Pseudo-elements add decoration without cluttering your HTML with extra tags: an arrow after a link, a quote mark before a testimonial, a small coloured line under a heading. Because they're only visual, keep important text in the real HTML.
::beforeand::after- add content before or after the element (they needcontent)::placeholder- the hint text in an input::first-letter,::selection- the first letter, or the text you select
Example
<!DOCTYPE html>
<html>
<head>
<style>
.new::after { content: " NEW"; color: #fff; background: #16a34a; font-size: 11px;
padding: 2px 6px; border-radius: 4px; margin-left: 6px; }
.done::before { content: "✓ "; color: green; }
p::first-letter { font-size: 2em; color: #7c3aed; }
::selection { background: #fde68a; }
</style>
</head>
<body>
<h3 class="new">Color Clash game</h3>
<p class="done">HTML lessons finished</p>
<p>Once upon a time, a coder learned CSS.</p>
</body>
</html>▶ Try it yourselfNever remove the keyboard focus outline without giving a clear
:focus-visible style instead. Keyboard users need to see where they are.Key points
- :hover, :focus-visible, :nth-child() style states and positions.
- ::before and ::after add decoration (they need content).
- Always keep a visible focus style for keyboard users.
📝 Test yourself
1. Which pseudo-class styles a button when the mouse is over it?
2. What does ::before need to show anything?
3. Fill in the pseudo-class for every second table row:
tr:nth-child() { background: #eee; }
