Pseudo-classes & Pseudo-elements
Style elements based on state (hover, focus, nth-child) and inject decorative content with ::before/::after.
What you will learn
- Use interactive and structural pseudo-classes
- Use ::before and ::after with content
- Build common effects
Pseudo-classes — style by state or position
| Pseudo-class | Matches |
|---|---|
:hover | Mouse over |
:focus | Has keyboard focus |
:first-child / :last-child | First / last among siblings |
:nth-child(even) | Every second element |
:nth-child(3) | The third element |
<style>
li:nth-child(odd) { background:#eef2ff; }
li:hover { background:#4338ca; color:#fff; }
li { padding:10px; list-style:none; }
</style>
<ul>
<li>Item one</li><li>Item two</li><li>Item three</li><li>Item four</li>
</ul>A pseudo-class is an extra condition (after a colon) that says “only when this is true”. li:nth-child(odd) matches the 1st, 3rd, 5th... items and gives them a light background — instant zebra stripes. li:hover matches whichever item the mouse is currently over and flips it to indigo with white text. Notice you did not add any classes to the HTML; the pseudo-classes target items by their position and state automatically.
Pseudo-elements — inject content
::before and ::after create extra “virtual” elements you can style. They need a content property. Great for icons, decorations and badges.
<style>
.note::before { content: "💡 "; }
.req::after { content: " *"; color:#ef4444; font-weight:700; }
.tag { position:relative; display:inline-block; background:#e0e7ff; padding:10px 14px; border-radius:8px; }
</style>
<p class="note">A tip with an auto icon.</p>
<label class="req">Required field</label>A pseudo-element creates a brand-new bit of content that is not in your HTML. .note::before inserts a 💡 emoji before the paragraph’s text, and .req::after inserts a red * after the label — perfect for marking required fields without editing the HTML. The rule both must follow: a pseudo-element only appears if you give it a content: value (even content: "" for a purely decorative shape). ::before goes in front, ::after goes behind.
Tip: ::before and ::after are everywhere in real CSS — tooltips, custom bullets, decorative quotes, “required” asterisks, ribbons. Always pair them with content:.
Q. Which pseudo-element adds content AFTER an element’s content?
✍️ Practice
- Stripe a list with
:nth-child(odd)and add a hover colour. - Add a red asterisk after required labels using
::afterandcontent.
🏠 Homework
- Add a decorative
::beforeicon to each item in a features list.