::after

The ::after pseudo-element in CSS allows you to insert generated content at the end of an element’s content. It’s often used for decorative purposes, such as adding icons, borders, or clearfixes.

Basic Syntax

selector::after {
  /* CSS properties */
}
  • selector: The element you want to apply the pseudo-element to.
  • ::after: The pseudo-element itself.
  • CSS properties: Any valid CSS properties to style the generated content.

Common Use Cases

Adding Icons or Characters

p::after {
  content: "\2714"; /* Checkmark character */
  color: green;
  font-size: 20px;
}

Creating Clearfixes

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

Generating Content Based on Element Content

p::after {
  content: attr(data-tooltip);
  display: none;
  position: absolute;
  top: -20px;
  left: 0;
  background-color: #f9f9f9;
  border: 1px solid #ccc;
  padding: 5px;
  z-index: 999;
}

This example creates a tooltip based on the data-tooltip attribute of the p element.

Important Properties

  • content: Specifies the generated content. Can be text, images, or even counters.
  • display: Determines the display type of the generated content (inline, block, etc.).
  • position: Allows you to position the generated content relative to its parent element.
  • clear: Used for clearfixes to prevent floating elements from affecting layout.

Example

<p>This is a paragraph with a checkmark.</p>
p::after {
  content: "\2714";
  color: green;
  font-size: 20px;
  margin-left: 5px;
}

This will add a green checkmark after the text of the paragraph.

Additional Notes

  • Specificity: Remember that ::after has low specificity, so you might need to override styles with more specific selectors.
  • Browser Compatibility: While ::after is widely supported, older browsers might require the :after syntax for compatibility.