CSS ::before Pseudo Element

The ::before pseudo-element is a generated content element that adds any kind of element before the content. It can be used to insert any kind of content, including characters, strings of text, and images. The value is defined by the content property.

By default, the ::before pseudo-element is inline.

This pseudo-element can be animated, positioned or floated like any other content.

The ::before pseudo-element can also be used with one colon notation :before which is supported by all browsers as well.

The ::after pseudo-class adds content after any other content wheareas the ::before pseudo-element adds content before any other content in HTML.

The pseudo-elements that are created with ::after and ::before do not apply to replaced elements (e. g., <br>, <img>).

Version

CSS Pseudo-Elements Level 4

Selectors Level 3

Syntax

::before {
  css declarations;
}

Example of the ::before pseudo-element:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p::before { 
        content: "  William Shakespeare -";
      }
    </style>
  </head>
  <body>
    <h2>::before selector example</h2>
    <p>"Be or not to be".</p>
  </body>
</html>

In the following example, the user can add styles to the content.

Example of the ::before pseudo-element with styled content:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p::before { 
        content: "William Shakespeare-";
        background-color: #ccc;
        color: #666;
        border: 2px dotted #000;
      }
    </style>
  </head>
  <body>
    <h2>::before selector example</h2>
    <p>"Be or not to be".</p>
  </body>
</html>

Browser support

chrome edge firefox safari opera
4.0+ 12.0+ 2.0+ 3.1+ 10.0+

Practice Your Knowledge

What does the '::before' pseudo-element do in CSS?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?