CSS ::before

The ::before pseudo-element in CSS is a powerful feature that allows you to insert content before an element's actual content. This is particularly useful for adding decorative elements or icons without requiring additional markup in your HTML.

To use ::before, you need to define it in your CSS stylesheet. The ::before pseudo-element is often used in conjunction with the content property, which specifies what content you want to insert.

Basic Syntax

The syntax for using ::before looks like this:


selector::before {
    content: 'something';
    /* Other styles */
}

Example: Adding a Decorative Bullet Point

In the following example, we will add a decorative bullet point before each list item using the ::before pseudo-element.


<style>
.example ul {
list-style-type: none;
}

.example li::before {
content: '•';
color: red;
font-size: 24px;
margin-right: 10px;
}
</style>

<ul>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>

Result:
  • Item One
  • Item Two
  • Item Three

Example: Prefixing Text

In this example, we will add a prefix before a heading.



    h2::before {
        content: 'Note: ';
        color: blue;
        font-weight: bold;
    }


<h2>Important Information</h2>
Result:

Important Information

Conclusion

The ::before pseudo-element is a versatile tool in CSS that allows for creative manipulation of content without changing your HTML structure. By making use of the content property, you can easily enhance your web pages' visual aesthetics.