CSS Selectors

Generated Content

Browser compatibility
Chrome Firefox (Gecko) Internet Explorer Opera Safari
1 1.0 8 4 4

The ::before and ::after pseudo-element selectors allow you to inject content before or after the contents of the targeted elements. You can think of this content as separate inline elements that can be styled independently of the existing element’s content. To generate the content you must use the content property, which can accept strings, url() for images, counter values, and the attribute function attr() which returns the value of a specified attribute as a string value. Since the generated content can be styled independently, it’s also acceptable to use a background-image rather than the url() function.

Syntax

As a structural pseudo-element selectors, before and after is preceded by two colons (::). To make either element specific, you can place a simple selector prior to the colons with no whitespace. Within the rule declaration the content property must be present to generate content. The content property will accept string values in quotations, the url() function, the counter() function for numbering items like lists, and keywords like open-quote and close-quote. The double colon syntax was added to the CSS Selectors Level 3 specfication as a way to distinguish pseudo-element selectors from pseudo-class selectors. Many designers still use the single colon syntax as a way to be backwards compatible with older browsers. There is no penalty for using the older syntax.


p::before {
  content: "hello";
    }

p::after {
  content: "hello";
    }  
 
Before and After selectors

Example:

At first glance generated content might seem like a curious oddity rather than something you would use frequently. However, the ability to inject icons, phrases, tips, or extra data outside the DOM is quite powerful. By using classes with generated content, you can add complex styling and add meaning without modifying your existing markup. 

To learn more about generated content, visit the W3C’s section on generated content in the CSS 2.1 Specification. Although fairly technical, this section covers generated content in detail and gives all the possible syntax values. Using generated content typically requires a good deal of practice before you are comfortable with it, so be sure to experiment with it before using it in production.