Using before and after Pseudo-elements

What a Pseudo-element Is

Unlike a pseudo-class (which targets an existing element in a certain state), a pseudo-element lets CSS create and style a piece of content that is not a real element in the HTML at all. ::before and ::after insert generated content just inside an element, at its start or end.

The Required content Property

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

Without a content property, ::before and ::after do not render at all - even an empty string, content: "";, is required to make them appear.

Adding Decorative Shapes Without Extra Markup

.quote::before {
  content: "\201C"; /* an opening curly quote character */
  font-size: 2rem;
  color: #cccccc;
}

This is a common technique for adding decorative quotation marks, icons, or small shapes without cluttering the HTML with extra empty <span> elements purely for styling purposes.

A Classic Use: The Clearfix Hack

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

Before Flexbox and Grid existed, this was the standard way to fix a container collapsing to zero height when it only contained floated children.

Things to Remember

  • Generated content is not part of the accessible DOM by default and is generally ignored by screen readers - never put essential information only inside content.
  • ::before and ::after are inline by default; setting display: block or inline-block is often needed to size or position them.
  • They cannot be added to certain elements, such as <img>, which have no way to render child content.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.