CSS ::before Pseudo Element
Use the ::before CSS pseudo-element for adding elements before the content. Read about the pseudo-element and try examples.
The ::before pseudo-element is a generated content element that inserts any kind of content before the content of an element. It can be used to insert 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 the single-colon notation :before, which is supported by all browsers.
The ::after pseudo-element adds content after any other content, whereas the ::before pseudo-element adds content before any other content in HTML.
Version
Syntax
CSS ::before Pseudo Element
::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-";
display: inline-block;
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>For purely decorative pseudo-elements, always set content: '' to ensure they render correctly across all browsers.
Practice
What does the '::before' pseudo-element do in CSS?