8.5 Pseudo Elements

Another of the great features of CSS is that pseudo-elements can be used to add special effects to some selectors. The basic syntax for this is:

selector:pseudo-element {property:value;}

The basic pseudo elements are:

Pseudo ElementDescriptionCSS
:afterAdds content after an element2
:beforeAdds content before an element2
:first-letterAdds a style to the first character of a text1
:first-lineAdds a style to the first line of a text1

The :after Pseudo-element

The :after pseudo-element can be used to insert some content after the content of an element. For example, if we wished to insert an image after each <h1> element:

h1:after	{content:url(tick.gif);}

The :before Pseudo-element

The :before pseudo-element can be used to insert some content before the content of an element. For example; if we wished to insert an image before each <h1> element:

h1:before	{content:url(tick.gif);}

The :first-line Pseudo-element

The first-line pseudo-element can be used to add a special style to the first line of some text. It can only be used with block-level elements, such as the paragraph tag for example.

p:first-line {
		color:#ff0000;
		font-variant:small-caps;
		}

In this example a browser will format the first line of the paragraph text as shown above. Subsequent lines of text will be rendered differently to other rules, and of course where the line breaks depends upon the size of the browser window.

The following properties can be used with the first-line pseudo-element:

  • font properties
  • color properties 
  • background properties
  • word-spacing
  • letter-spacing
  • text-decoration
  • vertical-align
  • text-transform
  • line-height
  • clear

The :first-letter Pseudo-element

The "first-letter" pseudo-element can be used to add a special style to the first letter of some text. Again this can only be used with block-level elements:

p:first-letter		{
			color:#ff0000;
			font-size:16px;
			}

The following properties apply to the "first-letter" pseudo-element:

  • font properties
  • color properties 
  • background properties
  • margin properties
  • padding properties
  • border properties
  • text-decoration
  • vertical-align (only if "float" is "none")
  • text-transform
  • line-height
  • float
  • clear