CSS Pseudo-Elements

Pseudo-Elements not only target a specific HTML element, they target a specific part of an element, for example, the first letter or line of an element, and can even be used to insert content before or after the content of an element. A Pseudo-Element takes the following form.

selector:pseudo-element {
   property: value;
}

::before and ::after Pseudo-Elements

The ::before and ::after Pseudo-Elements are used to add content before and after the actual content of an element, whilst still being within the element. The example below targets all 'h1' elements and places '>> ' before the content of the heading element.

CSS:

h1::before {
   content: ">> ";
}

As well as being able to add textual content, it is also possible to add an image, as shown in the below example of the ::after Pseudo-Element, where the image 'star.png' is displayed at the end of the content in an 'h1' element. Note that if the image does not reside in the same location as the web page in question, then the path to the image would need to be included in the CSS below.

CSS:

h1::after {
   content: url(star.png);
}

::first-letter and ::first-line Pseudo-Elements

The ::first-letter Pseudo-Element can be used to style the first letter of text inside an element, such as a paragraph, differently from the remaining text. In the example below the first letter in a paragraph is twice the size of the rest of the text in the paragraph.

CSS:

p::first-letter {
   font-size: 200%;
}

The ::first-line Pseudo-Element can be used to style the first line of an element, such as a paragraph, differently from the rest of the text. Note that first line refers to the text up to the first line break in the paragraph and not the first sentence of the paragraph. The below example makes the text italic in the first line of a paragraph.

CSS:

p::first-line {
   font-style: italic;
}

More Pseudo-Elements

The above Pseudo-Elements are just a selection of what is available. For details of more Pseudo-Elements, see the links below.