totn CSS

CSS :before selector

This CSS tutorial explains how to use the CSS selector called :before with syntax and examples.

Description

The CSS :before selector allows you to add content before a selected element.

Syntax

The syntax for the :active CSS selector is:

element:before { style_properties }

Parameters or Arguments

element
The type of element that you wish to add content before.
style_properties
The CSS styles to apply to the added content.

Note

  • The :before selector is a pseudo-class that allows you to add content before a selected element.
  • This element is an inline element.

Browser Compatibility

The CSS :before selector has basic support with the following browsers:

  • Chrome
  • Firefox (Gecko)
  • Internet Explorer 8+ (IE 8+)
  • Opera 4+
  • Safari (WebKit)

Example

We will discuss the :before selector below, exploring examples of how to use this selector in CSS to add content and apply styling to that new content.

With <p> tag

Let's look at a CSS :before example where we apply the :before selector to a <p> tag.

The CSS would look like this:

p:before { content: "> "; color: red; font-size: 10px; }

The HTML would look like this:

<div>
  <p>This is the first paragraph written by techonthenet.com.</p>
  <p>Here is the second paragraph written by techonthenet.com.</p>
</div>

The result would look like this (The :before selector would style the <p> tags as follows):

CSS

In this CSS example, the :before selector would add the text "> " in small red font before each of the paragraphs.

With <div> tag

Let's look at a CSS :before example where we apply the :before selector to a <div> tag.

The CSS would look like this:

div:before { content: "Example by techonthenet.com"; color: blue; font-style: italic; }

The HTML would look like this:

<div>
  <p>This is the first paragraph in the first div.</p>
  <p>Here is the second paragraph in the first div.</p>
</div>
<div>
  <p>Finally, this is the first paragraph in the second div.</p>
</div>

The result would look like this: (:before selector would style the <div> tags as follows):

CSS

In this CSS example, the :before selector would add the text "Example by techonthenet.com" in blue italicized font before each of the <div> tags.