::before / ::after

Avatar of Sara Cope
Sara Cope on (Updated on )

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

The ::before and ::after pseudo-elements in CSS allows you to insert content onto a page without it needing to be in the HTML. While the end result is not actually in the DOM, it appears on the page as if it is, and would essentially be like this:

div::before {
  content: "before";
}
div::after {
  content: "after";
}
<div>
  before
  <!-- Rest of stuff inside the div -->
  after
</div>

The only reasons to use one over the other are:

  • You want the generated content to come before the element content, positionally.
  • The ::after content is also “after” in source-order, so it will position on top of ::before if stacked on top of each other naturally.

Note that the content is still inside the element they are applied to. The naming sort of feels like they might come, ya know, before or after the element, but it’s really before or after the other content inside.

The value for content can be:

  • A string: content: "a string"; — special characters need to be specially encoded as a unicode entity. See the glyphs page.
  • An image: content: url(/path/to/image.jpg); — The image is inserted at it’s exact dimensions and cannot be resized. Since things like gradients are actually images, a pseudo element can be a gradient.
  • Nothing: content: ""; — Useful for clearfixes and inserting images as a background-image (set width and height, and can even resize with background-size).
  • A counter: content: counter(li); — Really useful for styling lists (but we also have ::marker for that).
  • A line break: content: "Killing \A Me \A Softly"; — Great for when you really need one.

Note that you can insert HTML entities in the content property, but no dice as far as them rendering or anything like that.

content: "<h1>I will not render as a Heading 1</h1>";

: vs ::

Every browser that supports the double colon (::) CSS3 syntax also supports just the (:) syntax, but Internet Explorer (IE) 8 only supports the single-colon, so for now, it’s recommended to just use the single-colon for best browser support.

:: is the newer format intended to distinguish pseudo content from pseudo-selectors. If you don’t need IE 8 support, feel free to use the double-colon.

Browser support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
429123.1

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
1151152.13.2

Tricks that use ::before and after

More information