12 Generated content and automatic numbering

Contents

In some cases, authors may want user agents to render content that does not come from the document tree. One familiar example of this is a numbered list; the author does not want to list the numbers explicitly, he or she wants the user agent to generate them automatically. Similarly, authors may want the user agent to insert the word "Figure" before the caption of a figure, or "Chapter 7" before the seventh chapter title. For audio or braille in particular, user agents should be able to insert these strings.

In CSS2, content may be generated by several mechanisms:

Below we describe the mechanisms associated with the 'content' property.

12.1 The :before and :after pseudo-elements

Authors specify the style and location of generated content with the :before and :after pseudo-elements. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted. As their names indicate, the :before and :after pseudo-elements specify content before and after an element's document tree content.

For example, the following rules insert the keyword "Note: " before the content of every P element whose "class" attribute has the value "note":

P.note:before { content: "Note: " }

The rendering objects (e.g., boxes) generated by an element include generated content. So, for example, changing the above style sheet to:

P.note:before { content: "Note: ";
                border: solid green}

would cause a solid green border to be rendered around the entire paragraph, including the initial string.

The :before and :after pseudo-elements inherit any inheritable properties from the element in the document tree to which they are attached.

For example, the following rules insert an open quote mark before every Q element. The color of the quote mark will be red, but the font will be the same as the font of the rest of the Q element:

Q:before {
  content: open-quote;
  color: red
}

In a :before or :after pseudo-element declaration, non-inherited properties take their initial values.

So, for example, because the initial value of the 'display' property is 'inline', the quote in the previous example is inserted as an inline box (i.e., on the same line as the element's initial text content). The next example explicitly sets the 'display' property to 'block', so that the inserted text becomes a block:

BODY:after {
    content: "The End";
    display: block;
    margin-top: 2em;
    text-align: center;
}

Note that an audio user agent would speak the words "The End" after rendering the rest of the BODY content.

User agents must ignore the following properties with :before and :after pseudo-elements: 'position', 'float', list properties, and table properties.

The :before and :after pseudo-elements elements allow values of the 'display' property as follows:

Note. Other values may be permitted in future levels of CSS.

12.2 The 'content' property

'content'
Value:  [ <string> | <uri> | <counter> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
Initial:  empty string
Applies to:  :before and :after pseudo-elements
Inherited:  no
Percentages:  N/A
Media:  all

This property is used with the :before and :after pseudo-elements to generate content in a document. The 'display' property controls whether the content is placed in an inline or block box.

The values have the following meanings:

<string>
Text content.
<uri>
The value is a URI that designates an external resource. If a user agent cannot support the resource because of the media types it supports, it must ignore the resource. Note. CSS2 offers no mechanism to change the size of the embedded object, or to provide a textual description, like the "alt" or "longdesc" attributes do for images in HTML. This may change in future levels of CSS.
<counter>
Counters may be specified with two different functions: 'counter()' or 'counters()'. The former has two forms: 'counter(name)' or 'counter(name, style)'. The generated text is the value of the named counter at this point in the rendering structure, in the indicated style ('decimal' by default). The latter also has two forms: 'counter(name, string)' or 'counter(name, string, style)'. The generated text is the value of all counters with the given name at this point in the rendering structure, separated by the specified string. The counters are rendered in the indicated style ('decimal' by default).
open-quote and 'close-quote'
Both of these values are replaced by the appropriate string from the 'quotes' property.
no-open-quote and no-close-quote
Inserts nothing (the empty string), but increments, resp. decrements the level of nesting for quotes.
attr(X)
This function returns the value of attribute X as a string. The string is not parsed by the CSS processor. If the current element doesn't have an attribute X, an empty string is returned. The case-sensitivity of attribute names depends on the document language.

Authors should put 'content' declarations in @media rules when the content requires media consideration. For instance, literal text may be used for any media group, but images only apply to the visual, bitmap media groups, and sound files only apply to the aural media group.

The following rule causes a sound file to be played at the end of a quotation (see the section on aural style sheets for additional mechanisms):

@media aural {
   BLOCKQUOTE:after {content: url(beautiful-music.wav)}
   }

The next rule inserts the text of the HTML "alt" attribute before the image. If the image is not displayed, the reader will still see the "alt" text.

IMG:before {content: attr(alt)}

Authors may include newlines in the generated content by writing the "\A" escape sequence in one of the strings after the 'content' property. This inserts a forced line break, similar to the BR element in HTML. See "Strings" and "Characters and case" for more information on the "\A" escape sequence.

Example:

H1:before {
    display: block;
    text-align: center;
    content: "chapter\A hoofdstuk\A chapitre"
}

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

Note. In future levels of CSS, the 'content' property may accept additional values, allowing it to vary the style of pieces of the generated content, but in CSS2, the content of the :before or :after pseudo-element all has the same style.

12.3 Interaction of :before and :after with 'compact' and 'run-in' elements

The following cases can occur:

  1. A 'run-in' or 'compact' element has a :before pseudo-element of type 'inline': the pseudo-element is taken into account when the size of the element is computed (for 'compact') and is rendered inside the same block box as the element.
  2. A 'run-in' or 'compact' element has an :after pseudo-element of type 'inline': ditto.
  3. A 'run-in' or 'compact' element has a :before pseudo-element of type 'block': the pseudo-element is rendered as a block above the element, and does not take part in the computation of the element's size (for 'compact').
  4. A 'run-in' or 'compact' element has an :after pseudo-element of type 'block': both the element and its :after pseudo-element are rendered as block boxes. The element is not rendered as an inline box in its own :after pseudo-element.
  5. The element following a 'run-in' or 'compact' element has a :before of type 'block': the decision how to render the 'run-in'/'compact' element is made with respect to the block box resulting from the :before pseudo-element.
  6. The element following a 'run-in' or 'compact' element has an :before of type 'inline': the decision how to render the 'run-in'/'compact' element depends on the type of the element to which the :before is attached.

Here is an example of a 'run-in' header with an :after pseudo-element, followed by a paragraph with a :before pseudo-element. All pseudo-elements are inline (the default) in this example. When the style sheet:

H3 { display: run-in }
H3:after { content: ": " }
P:before { content: "... " }

is applied to this source document:

<H3>Centaurs</H3>
<P>have hoofs
<P>have a tail

The visual rendering will resemble:

Centaurs: ... have hoofs
... have a tail

12.4 Quotation marks

In CSS2, authors may specify how user agents should render quotation marks in a style-sensitive and context-dependent manner. The 'quotes' property specifies pairs of quotation marks for each level of embedded quotation. The 'content' property gives access to those quotation marks and causes them to be inserted before and after a quotation.

12.4.1 Specifying quotes with the 'quotes' property

'quotes'
Value:  [<string> <string>]+ | none | inherit
Initial:  depends on user agent
Applies to:  all elements
Inherited:  yes
Percentages:  N/A
Media:  visual

This property specifies quotation marks for any number embedded quotations. Values have the following meanings:

none
The 'open-quote' and 'close-quote' values of the 'content' property produce no quotations marks.
[<string>  <string>]+
Values for the 'open-quote' and 'close-quote' values of the 'content' property are taken from this list of pairs of quotation marks (opening and closing). The first (leftmost) pair represents the outermost level of quotation, the second pair the first level of embedding, etc. The user agent must apply the appropriate pair of quotation marks according to the level of embedding.

For example, applying the following style sheet:

/* Specify pairs of quotes for two levels in two languages */
Q:lang(en) { quotes: '"' '"' "'" "'" }
Q:lang(no) { quotes: "" "" "'" "'" } 

/* Insert quotes before and after Q element content */
Q :before { content : open-quote }
Q :after  { content : close-quote }

to the following HTML fragment:

<HTML lang="en">
  <BODY>
    <P><Q>Quote me!</Q>
  </BODY>
</HTML>

would allow a user agent to render:

"Quote me!"

while this HTML fragment:

<HTML lang="no">
  <BODY>
    <P><Q>Han sa <Q>vet ikke</Q>!</Q>
  </BODY>
</HTML>

would produce:

Han sa 'vet ikke'!

Note. While the quotation marks specified by 'quotes' in the previous examples are conveniently located on computer keyboards, high quality typesetting would require different ISO 10646 characters. The following informative table lists some of the ISO 10646 quotation mark characters:

Ascii approximationISO 10646 code (hex)Description
"0022QUOTATION MARK [the ASCII double quotation mark]
'0027APOSTROPHE [the ASCII single quotation mark]
[<]2039SINGLE LEFT-POINTING ANGLE QUOTATION MARK
[>]203ASINGLE RIGHT-POINTING ANGLE QUOTATION MARK
00ABLEFT-POINTING DOUBLE ANGLE QUOTATION MARK
00BBRIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
[`]2018LEFT SINGLE QUOTATION MARK [single high-6]
[']2019RIGHT SINGLE QUOTATION MARK [single high-9]
[``]201CLEFT DOUBLE QUOTATION MARK [double high-6]
['']201DRIGHT DOUBLE QUOTATION MARK [double high-9]
[,,]201EDOUBLE LOW-9 QUOTATION MARK [double low-9]

12.4.2 Inserting quotes with the 'content' property

Quotation marks are inserted in appropriate places in a document with the 'open-quote' and 'close-quote' values of the 'content' property. Each occurrence of 'open-quote' or 'close-quote' is replaced by one of the strings from the value of 'quotes', based on the depth of nesting.

'Open-quote' refers to the first of a pair of quotes, 'close-quote' refers to the second. Which pair of quotes is used depend on the nesting level of quotes: the number of occurrences of 'open-quote' in all generated text before the current occurrence, minus the number of occurrences of 'close-quote'. If the depth is 0, the first pair is used, if the depth is 1, the second pair is used, etc. If the depth is greater than the number of pairs, the last pair is repeated.

Note that this quoting depth is independent of the nesting of the source document or the rendering structure.

Some typographic styles require open quotation marks to be repeated before every paragraph of a quote spanning several paragraphs, but only the last paragraph ends with a closing quotation mark. In CSS, this can be achieved by inserting "phantom" closing quotes. The keyword 'no-close-quote' decrements the quoting level, but does not insert a quotation mark.

The following style sheet puts opening quotation marks on every paragraph in a BLOCKQUOTE, and inserts a single closing quote at the end:

BLOCKQUOTE P:before { content: open-quote }
BLOCKQUOTE P:after { content: no-close-quote }
BLOCKQUOTE P.last:after { content: close-quote }

This relies on the last paragraph being marked with a class "last", since there are no selectors that can match the last child of an element.

For symmetry, there is also a 'no-open-quote' keyword, which inserts nothing, but increments the quotation depth by one.

Note. If a quotation is in a different language than the surrounding text, it is customary to quote the text with the quote marks of the language of the surrounding text, not the language of the quotation itself. For example, French inside English:

The device of the order of the garter is “Honi soit qui mal y pense.”
English inside French:
Il disait:  Il faut mettre l'action en ‹ fast forward ›.

A style sheet like the following will set the 'quotes' property so that 'open-quote' and 'close-quote' will work correctly on all elements. These rules are for documents that contain only English, French, or both. One rule is needed for every additional language. Note the use of the child combinator (">") to set quotes on elements based on the language of the surrounding text:

[LANG|=fr] > *  {quotes: "" "" "\2039" "\203A"}
[LANG|=en] > *  {quotes: "\201C" "\201D" "\2018" "\2019"}

The quotation marks for English are shown here in a form that most people will be able to type. If you can type them directly, they will look like this:

[LANG|=fr] > * {quotes: "" "" "‹" "›"}
[LANG|=en] > * {quotes: "“" "”" "‘" "’"}

12.5 Automatic counters and numbering

Automatic numbering in CSS2 is controlled with two properties, 'counter-increment' and 'counter-reset'. The counters defined by these properties can be used to generate text for the 'content' property (see the counter() function).

'counter-reset'
Value:  [ <identifier> <integer>? ]+ | none | inherit
Initial:  none
Applies to:  all elements
Inherited:  no
Percentages:  N/A
Media:  all
'counter-increment'
Value:  [ <identifier> <integer>? ]+ | none | inherit
Initial:  none
Applies to:  all elements
Inherited:  no
Percentages:  N/A
Media:  all

The 'counter-increment' property accepts one or more names of counters (identifiers), each one optionally followed by an integer. The integer indicates by how much the counter is incremented for every occurrence of the element. The default increment is 1. Zero and negative integers are allowed.

The 'counter-reset' property also contains a list of one or more names of counters, each one optionally followed by an integer. The integer gives the value that the counter is set to on each occurrence of the element. The default is 0.

If 'counter-increment' refers to a counter that is not in the scope (see below) of any 'counter-reset', the counter is assumed to have been reset to 0 by the root element.

This example shows a way to number chapters and sections with "Chapter 1", "1.1", "1.2", etc.

H1:before {
    content: "Chapter " counter(chapter) ". ";
    counter-increment: chapter;  /* Add 1 to chapter */
    counter-reset: section;      /* Set section to 0 */
}
H2:before {
    content: counter(chapter) "." counter(section) " ";
    counter-increment: section;
}

If an element increments/resets a counter and also uses it (in the 'content' property of its :before or :after pseudo-element), the counter is used after being incremented/reset.

If an element both resets and increments a counter, the counter is reset first and then incremented.

The 'counter-reset' property follows the cascading rules. Thus, due to cascading, the following stylesheet:

H1 {counter-reset: section -1}
H1 {counter-reset: imagenum 99}

will only reset 'imagenum'. To reset both counters, they have to be specified together:

H1 {counter-reset: section -1 imagenum 99}

12.5.1 Nested counters and scope

Counters are "self-nesting", in the sense that re-using a counter in a child element automatically creates a new instance of the counter. This is important for situations like lists in HTML, where elements can be nested inside themselves to arbitrary depth. It would be impossible to define uniquely named counters for each level.

Thus the following suffices to number nested list items. The result is very similar to that of setting 'display:list-item' and 'list-style: inside' on the LI element:

OL {counter-reset: item}
LI {display: block}
LI:before {content: counter(item) ". "; counter-increment: item}

The self-nesting is based on the principle that every element that has a 'counter-reset' for a counter X, creates a fresh counter X, the scope of which is the element, its younger siblings, and all the descendants of the element and its younger siblings.

In the example above, an OL will create a counter, and all children of the OL will refer to that counter.

If we denote by item[n] the nth counter, and by "(" and ")" the beginning and end of a scope, then the following HTML fragment will use the indicated counters. (We assume the style sheet as given in the example above).

<OL>               <!-- (set item[0] to 0          -->
  <LI>item         <!--  increment item[0] (= 1)   -->
  <LI>item         <!--  increment item[0] (= 2)   -->
    <OL>           <!--  (set item[1] to 0         -->
      <LI>item     <!--   increment item[1] (= 1)  -->
      <LI>item     <!--   increment item[1] (= 2)  -->
      <LI>item     <!--   increment item[1] (= 3)  -->
        <OL>       <!--   (set item[2] to 0        -->
          <LI>item <!--    increment item[2] (= 1) -->
        </OL>      <!--   )                        -->
        <OL>       <!--   (set item[3] to 0        -->
          <LI>     <!--    increment item[3] (= 1) -->
        </OL>      <!--   )                        -->
      <LI>item     <!--   increment item[1] (= 4)  -->
    </OL>          <!--  )                         -->
  <LI>item         <!--  increment item[0] (= 3)   -->
  <LI>item         <!--  increment item[0] (= 4)   -->
</OL>              <!-- )                          -->
<OL>               <!-- (reset item[4] to 0        -->
  <LI>item         <!--  increment item[4] (= 1)   -->
  <LI>item         <!--  increment item[4] (= 2)   -->
</OL>              <!-- )                          -->

The 'counters()' function generates a string composed of all counters with the same name, separated by a given string.

The following style sheet numbers nested list items as "1", "1.1", "1.1.1", etc.

OL {counter-reset: item}
LI {display: block}
LI:before {content: counters(item, "."); counter-increment: item}

12.5.2 Counter styles

By default, counters are rendered with decimal numbers, but all the styles available for the 'list-style-type' property are also available for counters. The notation is:

counter(name)

for the default, decimal style, or:

counter(name, 'list-style-type')

All the styles are allowed, including 'disc', 'circle', 'square', and 'none'.

Examples:

H1:before { content: counter(chno, upper-latin) ". " }
H2:before { content: counter(section, upper-roman) " - " }
BLOCKQUOTE:after { content: " [" counter(bq, hebrew) "]" }
DIV.note:before { content: counter(notecntr, disc) " " }
P:before { content: counter(p, none) }

12.5.3 Counters in elements with 'display: none'

An element that is not displayed ('display' set to 'none') cannot increment or reset a counter.

For example, with the following style sheet, H2s with class "secret" do not increment 'count2'.

H2.secret {counter-increment: count2; display: none}

Elements with 'visibility' set to 'hidden', on the other hand, do increment counters.

12.6 Markers

There are very few situations in CSS2 where an element causes the generation of more than one box. The most common case occurs for elements with 'display: list-item' (see the section on lists). The two generated boxes are the principal box (the list item content) and the list item marker (to the side of the principal box). Authors have very limited control of the style or position of the list item marker through the list style properties.

Markers are used together with the :before and :after pseudo-elements to offer similar functionality, but give authors more control over the position of the generated content. Markers may be used with automatic counters to create a wider variety of list styles than available with the list properties. They may also be used to create numbered margin notes, etc.

An element may generate two marker boxes: one for :before content and one for :after content, in addition to one principal box (that of the element's content). Marker boxes must only contain one line of content (i.e., one line box), so they are not as flexible as floats, which may be used to align entire blocks horizontally.

Marker boxes have padding and borders, but no margins.

To create a marker box for :before or :after content, the 'display' property must be given the value 'marker'. The marker box is only created if the 'content' property for the pseudo-element actually generates content. The content will be formatted as a single line.

For the :before pseudo-element, the baseline of text in the marker box will be vertically aligned with the baseline of text in the first line of content in the principal box. If the principal box contains no text, the top outer edge of the marker box will be aligned with the top outer edge of the principal box. For the :after pseudo-element, the baseline of text in the marker box will be vertically aligned with the baseline of text in the last line of content in the principal box. If the principal box contains no text, the bottom outer edge of the marker box will be aligned with the bottom outer edge of the principal box.

The vertical alignment of content within the marker box may be specified with the 'vertical-align' property.

The height of the :before marker and of the first line box of the principal box is computed as if they were a single line box. Analogously for the :after marker and the last line box. The 'line-height' property sets the height of the marker box.

The width of a marker box defaults to the natural width of its content, but may be specified with the 'width' property. If the width of a marker box's content is greater than the specified width, the 'overflow' property specifies overflow behavior. Marker boxes may overlap principal boxes.

If the 'width' is not 'auto', and is larger than the natural width, the 'text-align' property determines the horizontal alignment of the content in the marker box.

The 'marker-offset' property specifies the horizontal offset between a marker box and the associated principal box. The distance is measured between their nearest border edges.

When the 'display' property has the value 'marker' for content generated by an element with 'display: list-item', a marker box generated for ':before' replaces the normal list item marker.

The following example illustrates how markers may be used to add periods after each numbered list item. This HTML program and style sheet:

<HTML>
   <HEAD>
     <STYLE type="text/css">
	  LI:before { 
	      display: marker;
	      content: counter(mycounter, lower-roman) ".";
	      counter-increment: mycounter;
	  }   
     </STYLE>
  </HEAD>
  <BODY>
    <OL>
      <LI> This is the first item.
      <LI> This is the second item.
      <LI> This is the third item.
    </OL>
  </BODY>
</HTML>

should produce something like this:

   i. This is the first item.
  ii. This is the second item.
 iii. This is the third item.

This next example shows a different horizontal alignment: the content is centered within a box of a fixed width. This document:

 <HTML>
    <HEAD>
      <STYLE type="text/css">
           LI:before { 
               display: marker;
               content: "(" numeric(counter) ")";
               width: 6em;
               text-align: center;
           }   
      </STYLE>
   </HEAD>
   <BODY>
     <OL>
       <LI> This is the first item.
       <LI> This is the second item.
       <LI> This is the third item.
     </OL>
   </BODY>
 </HTML>

should produce something like this:

  (1)    This is the 
         first item.
  (2)    This is the 
         second item.
  (3)    This is the 
         third item.

The next example creates markers before and after list items. This document:

<HTML>
  <HEAD>
    <STYLE type="text/css">
      @media screen, print {
         LI:before { 
   	      display: marker;
	      content: url(smiley.gif);
         LI:after {
	      display: marker;
   	      content: url(sad.gif);
         }
      }
    </STYLE>
  </HEAD>
  <BODY>
    <UL>
      <LI>first list item comes first
      <LI>second list item comes second
    </UL>
  </BODY>
</HTML>

should produce something like this (ascii art is used instead of smiley gif images here):

  :-) first list item 
      comes first      :-(
  :-) second list item 
      comes second     :-(

The next example uses markers to number notes (paragraphs). The following document:

<HTML>
  <HEAD>
    <STYLE type="text/css">
      P { margin-left: 12 em; }
      @media screen, print {
         P.Note:before         { 
  	      display: marker;
	      content: url(note.gif) 
                       "Note " numeric(note-counter) ":";
              counter-increment: note-counter;
              text-align: left;
              width: 10em;
         }
     }
    </STYLE>
  </HEAD>
  <BODY>
    <P>This is the first paragraph in this document.</P>
    <P CLASS="Note">This is a very short document.</P>
    <P>This is the end.</P>
  </BODY>
</HTML>

should produce something like:

            This is the first paragraph 
            in this document.

  Note 1:   This is a very short 
            document.
           
            This is the end.
'marker-offset'
Value:  <length> | auto | inherit
Initial:  auto
Applies to:  elements with 'display' set to 'marker'
Inherited:  no
Percentages:  N/A
Media:  visual

This property specifies the distance between the nearest border edges of a marker box and its associated principal box. The offset may either be a user-specified (<length>) or chosen by the UA ('auto'). Lengths may be negative, but there may be implementation-specific limits.

The following example illustrates how markers may be used to add periods after each numbered list item. This HTML program and style sheet:

 <HTML>
    <HEAD>
      <STYLE type="text/css">
           LI:before { 
               display: marker;
               marker-offset: 3em;
               content: counter(mycounter, lower-roman) ".";
               counter-increment: mycounter;
           }   
      </STYLE>
   </HEAD>
   <BODY>
     <P> This is a long preceding paragraph ...
     <OL>
       <LI> This is the first item.
       <LI> This is the second item.
       <LI> This is the third item.
     </OL>
     <P> This is a long following paragraph ...
   </BODY>
 </HTML>

should produce something like this:

        This is a long preceding
        paragraph ...
      
   i.   This is the first item.
  ii.   This is the second item.
 iii.   This is the third item.

        This is a long following
        paragraph ...