The :before and :after pseudo-elements

For example, the following rule inserts the string "Note: " before the content of every P element whose "class" attribute has the value "note":

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

The formatting 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: " }
P.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.

Example(s):

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.

Example(s):

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:

  • If the subject of the selector is a block-level element, allowed values are 'none', 'inline', 'block', and 'marker'. If the value of the 'display' has any other value, the pseudo-element will behave as if the value were 'block'.
  • If the subject of the selector is an inline-level element, allowed values are 'none' and 'inline'. If the value of the 'display' has any other value, the pseudo-element will behave as if the value were 'inline'.