CSS Pseudo-element Selector

The CSS pseudo-element selector is used to style specific parts of an element or to insert content before or after an element’s content. Pseudo-elements allow more granular control of styling without requiring additional HTML elements.

The syntax for a pseudo-element selector is:

</>
Copy
selector::pseudo-element {
    property: value;
}

Where:

ParameterDescription
selectorThe element being styled.
pseudo-elementThe part of the element being targeted (e.g., ::before, ::after, ::first-letter).
propertyA CSS property (e.g., content, color, etc.).
valueThe value assigned to the CSS property.

Examples

Styling the First Letter of a Paragraph using ::first-letter Pseudo-element Selector

In this example, we style the first letter of every <p> element, making it larger and bold.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        p::first-letter {
            font-size: 2em;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <p>This is an example paragraph.</p>
</body>
</html>

Inserting Content Before an Element using ::before Pseudo-element Selector

Here, we use the ::before pseudo-element to add text content before every <h1> element.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        h1::before {
            content: "Important: ";
            color: red;
        }
    </style>
</head>
<body>
    <h1>CSS Tutorial</h1>
</body>
</html>

Adding Decorative Content After an Element using ::after Pseudo-element Selector

In this example, we use the ::after pseudo-element to add a decorative arrow after all <a> (anchor) elements.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        a::after {
            content: " →";
            color: gray;
        }
    </style>
</head>
<body>
    <a href="#">Learn More</a>
</body>
</html>

Highlighting the First Line of Text using ::first-line Pseudo-element Selector

In this example, we style the first line of text in every <p> element, changing its font style and color.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        p::first-line {
            font-style: italic;
            color: #555;
        }
    </style>
</head>
<body>
    <p>This is an example paragraph with a styled first line.</p>
</body>
</html>