iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Pseudo-element

A pseudo-element styles a part of an element — its first letter, the marker on a list item, generated content before or after. They use a double colon to set them apart from pseudo-classes.

Pseudo-elements you'll use

Pseudo-elementTargetsTypical use
::beforeA generated element at the start of the content.Icons, decorative quotes, custom bullets.
::afterA generated element at the end of the content.Same as ::before, opposite side.
::first-letterThe first character of the first line.Drop caps in editorial layouts.
::first-lineThe first line as the browser breaks it.Small-caps treatment.
::markerThe bullet or number of a list item.Recolour, resize, swap glyph.
::placeholderPlaceholder text in an input.Soft grey placeholder.
::selectionText the user has highlighted.Brand-coloured selection.

The classic ::before for icons

CSS
.external::after {
  content: " ↗";        /* required — even an empty string */
  color: #04AA6D;
  font-size: 0.9em;
}
Note: ::before and ::after only work if you also set a content property. Without it, the pseudo-element doesn't render.
Tip: Pseudo-class (:hover) = a state. Pseudo-element (::before) = a part. One colon vs two — same vocabulary, two ideas.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Pseudo-element</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Append a small green arrow after every link with class "external".

.external:: { content: ' \2197'; color: #04AA6D; }

Test yourself

Q1. Which pseudo-element inserts generated content at the end of an element?
Q2. For `::before` or `::after` to render, you must set…
Q3. Which pseudo-element styles highlighted text?

Discussion

Loading…