Skip to main content
Home / CSS Almanac / Selectors / A / ::before / ::after

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";
  <!-- Rest of stuff inside the 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 clearfix and inserting images as background-images (set width and height, and can even resize with background-size).
  • A counter: content: counter(li); – Really useful for styling lists until :marker comes along.

Note that you cannot insert HTML (at least, that will be rendered as HTML). content: "<h1>nope</h1>";

: vs ::

Every browser that supports the double colon (::) CSS3 syntax also supports just the (:) syntax, but 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.


Other Resources

Browser Support

Little issues:

  • Firefox 3.5- wouldn’t allow absolute positioning of pseudo elements.
  • In Opera 9.2, whitespace is always displayed within this pseudo-element as if it’s pre text.
  • IE 8 doesn’t support z-index on them
Chrome Safari Firefox Opera IE Android iOS
2+ 1.3+ 3.5+ 6+ 8+ Yep Yep
Jump to Almanac Navigation