Pseudo-elements

Style specific parts of an element with ::before and ::after.

Syntaxp::first-letter { } .badge::after { content: "!"; }

A pseudo-element styles a specific part of an element, written with a double colon.

  • ::first-line and ::first-letter — style parts of text.
  • ::before and ::after — insert generated content.
  • ::selection — style highlighted text.

The ::before and ::after pseudo-elements require a content property to appear.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A designer adds decorative quotation marks before and after blockquote text using ::before and ::after without touching the HTML.
  • A developer uses ::first-letter to enlarge and style the opening character of an article paragraph for a drop-cap editorial effect.
  • A developer uses ::placeholder to style the hint text color in form inputs to match the site's muted gray brand palette.

More examples

Decorative ::before and ::after

Inserts typographic quote characters around a blockquote using ::before and ::after with content property.

Example · css
blockquote::before {
  content: '\201C';
  font-size: 3em;
  color: #2965f1;
  line-height: 0;
  vertical-align: -0.4em;
}
blockquote::after {
  content: '\201D';
}

Drop-cap with ::first-letter

Targets only the first letter of the first paragraph in an article to create a classic magazine drop-cap effect.

Example · css
article p:first-of-type::first-letter {
  font-size: 3.5rem;
  font-weight: bold;
  float: left;
  line-height: 0.8;
  margin-right: 6px;
  color: #2965f1;
}

Custom placeholder styling

Styles the placeholder text and hides it on focus using ::placeholder to improve form readability.

Example · css
input::placeholder {
  color: #aaa;
  font-style: italic;
  font-size: 0.9rem;
}
input:focus::placeholder {
  opacity: 0;
}

Discussion

  • Be the first to comment on this lesson.
Pseudo-elements — CSS | SoundsCode