CSS Pseudo-Elements

Pseudo-elements can control the styling of specific parts of the elements. The pseudo-elements have a double colon before them and can be used by being added after the selectors like
selector::pseudo-element{…}
The pseudo-elements supported by CSS are:

  • ::first-line
  • ::first-letter
  • ::after
  • ::before
  • ::selection
  • ::first-line

This is to stylize the first line of the text content. You can alter the following for this element:

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

::first-letter

This element concerns the first letter of the text. In addition to above mentioned properties, first-letter can also by stylised for:

  • margin
  • padding
  • border
  • float

::before

This pseudo-element helps us to insert anything before the element content. You can insert an image before your text using ::before.

::after

It is the opposite of ::before. Here, you can add something after the element content.

::selection

The selection of text generally inverts the background and font color of the selected text. For example, if you select a black text on white background, it will turn to something like white text on black background. However, these effects can be changed in web-pages using the pseudo element ::selection. ::selection can help us set the background color as well as the font color of the selected text. The IE 8 and earlier versions don’t support this pseudo-elements.

Multiple pseudo elements

We can also combine the effects of the pseudo-elements. For example, if you want the first letter to be in one color and rest of the first line in another color, you can set both the ::first-letter and the ::first-line for that element. Similarly, you can combine the effects of first line with ::selection or add some image before or after the text using ::before and ::after.

Apart from this, you can also combine the pseudo element with the element classes. All have to do is mention the element then its class and finally the pseudo element, like:

selector.class::pseudo-element