CSS Tutorial · Beyond the Basics · Lesson 15 of 19
CSS Pseudo-classes and Pseudo-elements
:hover, :focus-visible, :nth-child, ::before, ::after and more.
Pseudo-classes — states
A pseudo-class selects elements in a particular state or position:
| Pseudo-class | Selects |
|---|---|
:hover, :active |
pointer over / pressing |
:focus-visible |
keyboard focus (show a clear focus ring!) |
:checked, :disabled, :invalid |
form states |
:first-child, :last-child, :nth-child(odd) |
position among siblings |
:not(.x) |
everything except |
<style>
body { font: 14px system-ui; }
button { padding: 8px 14px; border: 0; border-radius: 6px; background: #2563eb; color: white; cursor: pointer; }
button:hover { background: #1d4ed8; }
button:active { transform: scale(0.97); }
button:focus-visible { outline: 3px solid #f59e0b; outline-offset: 2px; }
li:nth-child(odd) { background: #f1f5f9; }
li:first-child { font-weight: bold; }
input:invalid { border-color: crimson; }
</style>
<button>Hover, click or tab to me</button>
<ul><li>First</li><li>Second</li><li>Third</li><li>Fourth</li></ul>
<input type="email" value="not-an-email">
Pseudo-elements — generated parts
::before and ::after insert decorative content; ::placeholder, ::selection and ::first-letter style parts of an element:
<style>
body { font: 15px system-ui; }
.required::after { content: " *"; color: crimson; }
.tip::before { content: "Tip: "; }
p.drop::first-letter { font-size: 2.2em; font-weight: bold; float: left; margin-right: 4px; color: #7c3aed; }
::selection { background: #fde68a; }
input::placeholder { color: #94a3b8; font-style: italic; }
</style>
<label class="required">Email</label> <input placeholder="[email protected]">
<p class="tip">Pseudo-elements add decoration without extra HTML.</p>
<p class="drop">Drop caps start long articles in style. Select this text to see the custom selection colour.</p>
Test yourself
Which pseudo-class should you use to style keyboard focus?
:hover:active:focus-visible:checked
Show answer
Answer: :focus-visible