Advanced Selectors & the CascadeExtra· 40 min read

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-classMatches
:hoverMouse over
:focusHas keyboard focus
:first-child / :last-childFirst / last among siblings
:nth-child(even)Every second element
:nth-child(3)The third element
Striped rows + hover with pseudo-classes
<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>
Live preview

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.

::before / ::after add content
<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>
Live preview

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?

Answer: ::after inserts a styleable pseudo-element after the element’s content (it requires a content property).

✍️ Practice

  1. Stripe a list with :nth-child(odd) and add a hover colour.
  2. Add a red asterisk after required labels using ::after and content.

🏠 Homework

  1. Add a decorative ::before icon to each item in a features list.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →