CSS :before pseudo-element

The CSS :before pseudo-element is used to insert content before an element's actual content. It creates a virtual element that appears as the first child of the selected element, allowing you to add decorative or informational content without modifying the HTML structure.

Syntax

selector:before {
    content: value;
    /* other properties */
}

Example 1: Adding Text Content

The following example demonstrates how to add text content before paragraph elements −

<!DOCTYPE html>
<html>
<head>
<style>
    p:before {
        content: "Note: ";
        font-weight: bold;
        color: #ff6b35;
    }
    
    p {
        margin: 10px 0;
        padding: 10px;
        background-color: #f9f9f9;
        border-left: 3px solid #ff6b35;
    }
</style>
</head>
<body>
    <p>This is the first paragraph with auto-generated prefix.</p>
    <p>This is the second paragraph with auto-generated prefix.</p>
    <p>This is the third paragraph with auto-generated prefix.</p>
</body>
</html>
Three paragraphs appear, each preceded by bold orange "Note: " text. The paragraphs have a light gray background with orange left borders.

Example 2: Adding Decorative Symbols

This example shows how to add decorative symbols before list items −

<!DOCTYPE html>
<html>
<head>
<style>
    .custom-list {
        list-style: none;
        padding: 0;
    }
    
    .custom-list li:before {
        content: "? ";
        color: #gold;
        font-size: 1.2em;
        margin-right: 8px;
    }
    
    .custom-list li {
        padding: 5px 0;
        font-size: 16px;
    }
</style>
</head>
<body>
    <ul class="custom-list">
        <li>First important item</li>
        <li>Second important item</li>
        <li>Third important item</li>
    </ul>
</body>
</html>
A list appears with golden star symbols (?) before each item instead of regular bullet points. Each item is spaced nicely with the decorative stars.

Key Points

  • The content property is required for :before to work
  • The pseudo-element is inline by default but can be styled with display property
  • Content can be text, images, or special characters
  • It doesn't modify the actual HTML structure

Conclusion

The :before pseudo-element is a powerful CSS feature for adding decorative or informational content without cluttering your HTML. It's commonly used for icons, prefixes, and custom styling elements.

Updated on: 2026-03-15T11:56:26+05:30

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements