Codectionary / Developer documentation / CSS

Pseudo-elements

Pseudo-elements let you style a specific part of an element rather than the whole thing, or insert generated content without adding extra HTML. ::before and ::after insert content before/after an element's actual content. ::first-line and ::first-letter target specific text portions. ::placeholder styles input placeholder text, and ::selection styles user-highlighted text.

Syntax

element::before { content: ""; }

Examples

::before and ::after

Inserting decorative content without extra markup - always requires the content property.

.required-label::after {
  content: " *";
  color: red;
}

.quote::before {
  content: "\201C"; /* opening curly quote character */
  font-size: 2em;
}

::first-letter and ::first-line

Styling just the beginning of a text block, like a drop cap.

.article p::first-letter {
  font-size: 3em;
  float: left;
  line-height: 0.8;
  margin-right: 4px;
}

::placeholder and ::selection

Styling input placeholder text and user text selection highlighting.

input::placeholder {
  color: #9ca3af;
  font-style: italic;
}

::selection {
  background: #fef08a;
  color: #000;
}

Parameters and values

  • ::before / ::after (pseudo-element): Inserts generated content, requires the content property
  • ::first-line / ::first-letter (pseudo-element): Targets the first line or letter of text
  • ::placeholder (pseudo-element): Styles an input's placeholder text
  • ::selection (pseudo-element): Styles user-highlighted text

Best practices

  • Always include a content property (even an empty string) on ::before/::after - without it, the pseudo-element does not render at all
  • Use ::before/::after for purely decorative content, not essential information - it is not reliably accessible to all assistive technology
  • Use double colons (::) for true pseudo-elements per the modern spec, though single colon (:before) still works for legacy compatibility
  • Use ::selection sparingly and ensure sufficient contrast - it affects how your content looks when users highlight text to copy it

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation