CSS: generated content tutorial

CSS generated content is specified through the :before and :after pseudo-elements and inserted into the page thanks to the content property. Generated content only belongs to the presentation layer of a document, meaning that it's not part of the DOM structure of the page. In other words, generated content displays some content but without modifying the document tree.

:before and :after pseudo-elements

The :before and :after pseudo-elements insert generated content before or after the actual content of an element. Thus if a paragraph contains the word 'Hello', the following declaration:

p:after {
  content: ' World';
}

will insert the word 'World' after the content of the given element so that you will read 'Hello World'. By default, generated content is displayed as inline, but you can change this default behavior using the display property. However, some CSS properties and values might not be available on some browsers.

In CSS3, these pseudo-elements must be written using a double colon (e.g ::before instead of :before)

The content property

In the content property, simple strings are treated literally, so:

'World'
' World'

The second of the two strings from above will also have a space before it and will be displayed as such. This property also accepts Unicode characters used to display special symbols and glyphs. The syntax is:

\escape-sequence

where escape-sequence is a sequence of 4 or 6 hexadecimal characters. For example, if you want to display an at-symbol, you can write:

a.twitter:before {
  content: '\0040 ';
}

For more on Unicode characters, check out the Alan Wood's site.

The content property also accepts four CSS functions within it:

url()
Inserts an image or another resource as generated content. It works like background-image
attr(value)
Inserts an element's attribute value, for example attr(id).
counter(counterName)
Inserts a named counter.
counters(counterName)
Inserts multiple nested counters.

Further reading

  1. Rediscovering generated content
  2. CSS counters

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “CSS: generated content tutorial”

Leave a Reply

Note: Only a member of this blog may post a comment.