🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

CSS Pseudo-Elements: ::before, ::after, and Type Effects

Web StylesđŸŸĸ Free Lesson

CSS Pseudo-Elements: ::before, ::after, and Type Effects

Where pseudo-classes select an element in a state, pseudo-elements select a fictional part of an element — its first letter, its first line, the text a user has highlighted, or a box that does not exist in the markup at all until content: conjures it. The double-colon ::before and ::after are the workhorses: they hang generated boxes off every element in the document, which is how you get quote marks around blockquotes, decorative underlines under headings, status dots before labels, and tooltips that never appear in a DOM inspector's element list. The rest of the family — ::first-letter, ::first-line, ::selection, ::placeholder, ::marker — style typographic slices that would otherwise need wrapper spans. Used deliberately, these tools delete markup; used thoughtlessly, they also avoid the accessibility traps that generated content is famous for.

The hidden requirement: content

::before and ::after generate nothing without a content property. An empty string counts, and so does content: "", which is the most common case: you want a box purely for styling — a gradient underline, an absolutely positioned dot — and the string exists only to make the pseudo-element render at all. Some values are specialized: open-quote and close-quote cooperate with the quotes property to produce language-appropriate quotation marks; attr(...) copies an attribute's value into the generated content; counter(...) and counters(...) insert numbering (covered in the counters lesson). Without content, the declaration is ignored entirely — a frequent source of "my ::after does nothing" confusion.

Decorative patterns that delete wrapper markup

The canonical markup-free trick is the underline that animates on hover. Without a pseudo-element you would wrap link text in a span with a background gradient; with one, the parent stays clean:

.link-animated {
  color: #1d4ed8;
  text-decoration: none;
  background-image: linear-gradient(currentColor, currentColor);
  background-size: 0% 2px;
  background-position: 0 100%;
  background-repeat: no-repeat;
  transition: background-size 0.25s ease;
}

.link-animated:hover,
.link-animated:focus-visible {
  background-size: 100% 2px;
}

.heading-accent {
  position: relative;
  display: inline-block;
  padding-block-end: 0.5rem;
}

.heading-accent::after {
  content: "";
  position: absolute;
  inset-inline-start: 0;
  bottom: 0;
  width: 3.5rem;
  height: 3px;
  border-radius: 2px;
  background: #2563eb;
}

.tag::before {
  content: "";
  display: inline-block;
  width: 0.5rem;
  height: 0.5rem;
  margin-inline-end: 0.5rem;
  border-radius: 50%;
  background: currentColor;
  vertical-align: 0.05em;
}

.tag.is-live { color: #16a34a; }
.tag.is-off { color: #dc2626; }

The underline example is doubly useful because it animates background-size, a paint-only property that does not trigger layout — the animation stays cheap. Note currentColor, which makes the pseudo-element inherit the element's text color in every theme, including dark mode.

Typography effects on document slices

::first-letter and ::first-line target a computed fragment of the element's first rendered letter or line — the letter or line, not a marked-up span, so they follow whatever the layout produces at any width. ::first-letter is the drop cap tool: float it left, set a multiple of the body size, tighten the line-height, and the paragraph wraps around it. Its allowed property set is intentionally limited to typographic and box properties; color, background, margin, padding, border, font, float, and line-height all work, but layout properties like display on some engines do not. ::first-line is even more restricted and more dynamic — the "line" changes when text reflows, so you cannot use it to style a specific phrase, only whatever happens to break first.

::selection styles highlighted text and accepts only color, background, text-decoration, and a few stroke properties. ::placeholder styles placeholder text; keep its contrast readable, because placeholder-as-label patterns are already an accessibility compromise. ::marker styles list bullets and counters — ::marker { color: #2563eb; font-weight: 700; } restyles every list item's bullet in one line, and lets you swap the marker entirely with content: "→".

Tooltips and badges with attr()

attr() reads a data attribute into generated content, enabling hover labels without a second element:

[data-tip] {
  position: relative;
}

[data-tip]::after {
  content: attr(data-tip);
  position: absolute;
  bottom: calc(100% + 6px);
  left: 50%;
  transform: translateX(-50%) translateY(4px);
  padding: 0.35rem 0.6rem;
  border-radius: 6px;
  background: #0f172a;
  color: #f8fafc;
  font-size: 0.75rem;
  line-height: 1.3;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.15s ease, transform 0.15s ease;
}

[data-tip]:hover::after,
[data-tip]:focus-visible::after {
  opacity: 1;
  transform: translateX(-50%) translateY(0);
}

.badge-count[data-count]::after {
  content: attr(data-count);
  position: absolute;
  top: -0.4rem;
  inset-inline-end: -0.4rem;
  min-width: 1.15rem;
  padding: 0 0.3rem;
  border-radius: 999px;
  background: #dc2626;
  color: #ffffff;
  font-size: 0.7rem;
  font-weight: 700;
  text-align: center;
}

The plain attr() used above returns a string, which is all you need for labels. The newer attr(name type fallback) syntax — with explicit types such as string, integer, or url, plus custom-property types and fallbacks — lets attr() feed real property values rather than only content, opening the door to attribute-driven layouts. Browser support for the typed form is still spreading, so keep it progressive: presentational strings first, typed values as enhancement.

Counters meet pseudo-elements

Numbered headings, definition lists, and step indicators all run through pseudo-elements because that is where content: counter() is legal. The pattern has three moves: counter-reset on the ancestor to create and initialize the variable, counter-increment on each item, and counter(...) inside a pseudo-element's content to display it. Format keywords change the numeral system — decimal, upper-roman, lower-alpha, decimal-leading-zero — and counter(item, upper-roman) chooses per use. The counters lesson goes deeper; the key structural point is that pseudo-elements are the display layer for numbering that lives in the cascade.

The accessibility and theming limits

Generated content is announced by most modern screen readers when it is purely textual — a content: "Required" marker will be read — but behavior has historically been inconsistent, so never put essential information only in ::before or ::after. Decorative shapes, icons, and repeated labels that also exist in accessible text are safe. Two more limits: pseudo-element content cannot be selected or copied like real text, and it is invisible to find-in-page. For theming, avoid hard-coding colors in generated boxes — use currentColor or custom properties so dark mode works. And remember that ::after on an element with overflow: hidden may be clipped, and an absolutely positioned pseudo-element still respects stacking contexts like any other box.

Finding generated boxes when something looks wrong

Because pseudo-elements have no node in the Elements panel by default, debugging them takes a different habit. In the Styles pane, the matched rules for an element list ::before and ::after alongside ordinary selectors — expand them to toggle the declaration on and off live. Chrome's Computed panel has a dedicated pseudo-element disclosure arrow showing the final computed box, which is the quickest way to confirm that content resolved and that the box actually has dimensions. A box with no width or height usually means the content was empty and the element was static; adding position or display restores it. The DOM tab's "Show pseudo-elements" filter, available in newer devtools, exposes them for inspection too.

Two visual checks catch most design-time surprises. First, toggle outline: 2px solid red on the pseudo-element to see its real footprint — often far larger than expected when an absolutely positioned tooltip inherits the wrong containing block. Second, verify stacking: generated boxes participate in normal stacking contexts, so a ::after sitting behind its parent's background usually needs either a higher z-index on the pseudo-element or removal of a stacking context on the parent. Keeping decorative pseudo-elements scoped with a dedicated class — rather than styling every ::after globally — makes both debugging steps considerably faster.

Common Mistakes

Pseudo-element does not render at all

Fix: Add a content declaration — content: "" is enough — because ::before and ::after generate nothing without it

Critical information lives only in generated content

Fix: Repeat essential text in the real DOM or an aria-label, and keep ::before and ::after for decoration and redundant labels

Tooltip built with attr() is unusable by keyboard users

Fix: Show it on :focus-visible as well as hover, keep pointer-events: none so it never blocks clicks, and prefer a real element for long content

Hard-coded colors in generated boxes break dark mode

Fix: Use currentColor or custom properties so the pseudo-element inherits the theme automatically

Best Practices

  • Use empty content: "" for purely decorative boxes and real strings only when the text adds meaning
  • Prefer animating transform and opacity on pseudo-elements to keep effects off the layout path
  • Apply ::first-letter for drop caps and ::marker for list restyling instead of wrapping spans in markup
  • Keep decorative pseudo-elements out of overflow: hidden containers unless clipping is intended
  • Pair every attr() tooltip with a :focus-visible state for keyboard accessibility

Interview Questions

Q1: Why does my ::after rule have no effect?

Almost always because the content property is missing. A pseudo-element with declarations but no content does not generate a box. Add content: "" for decorative boxes, or a string, attr(), counter(), or quote keyword for real text.

Q2: Can screen readers read content inserted by ::before and ::after?

Modern screen readers generally announce generated textual content, but support has not always been reliable across older combinations. Treat generated text as supplementary: never place information a user must have exclusively in a pseudo-element, and provide real text or an accessible name for essential content.

Q3: What is the difference between ::first-letter and ::first-line?

::first-letter styles the first rendered letter of a block and supports typographic and box properties, which is why drop caps work with float. ::first-line styles whatever text lands on the first line, so it changes on reflow and supports a much smaller property set — it cannot target a specific phrase, only the computed first line.

Key Takeaways

  • ::before and ::after require content to render; empty strings are valid and power most decorative boxes
  • Generated underlines, accents, dots, and counters replace wrapper spans and keep markup semantic
  • ::first-letter, ::first-line, ::selection, ::placeholder, and ::marker style typographic slices that markup cannot address cleanly
  • attr() pulls attribute values into content for CSS-only tooltips and badges
  • Keep essential information in the real DOM: generated content can be inconsistent for assistive tech and is unselectable
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement