CSS Pseudo-Element Selectors

CSS Pseudo-Element Selectors allow you to style a specific part of an HTML element or insert generated content before or after an element’s content. They are useful for creating decorative effects without adding extra HTML elements.

A pseudo-element is generally written using a double colon (::) followed by its name.

CSS Pseudo-Element Syntax

The basic syntax is:

selector::pseudo-element {
    property: value;
}

For example, p::first-letter selects the first letter of a paragraph.

Common CSS Pseudo-Elements

Pseudo-ElementDescription
::beforeInserts generated content before an element’s content
::afterInserts generated content after an element’s content
::first-letterStyles the first letter of a text block
::first-lineStyles the first formatted line of text
::selectionStyles text selected by the user
::placeholderStyles placeholder text in form controls
::markerStyles list-item markers, such as bullets and numbers

CSS Pseudo-Element Example

The following example uses ::first-letter and ::first-line.

<!DOCTYPE html>
<html>
<head>
    <title>CSS Pseudo-Element Example</title>
    <style>
        p::first-letter {
            color: blue;
            font-size: 32px;
            font-weight: bold;
        }

        p::first-line {
            color: green;
        }
    </style>
</head>
<body>
    <p>
        Welcome to Web4Learners.
        Learn HTML, CSS, and web development.
    </p>
</body>
</html>

The first letter of the paragraph becomes larger and blue. The first formatted line appears green. Depending on the available width and font size, the first letter may also be part of the first line.

Using ::before and ::after

The ::before and ::after pseudo-elements can insert decorative content through the CSS content property.

<h2 class="title">CSS Tutorials</h2>
.title::before {
    content: "★ ";
    color: orange;
}

.title::after {
    content: " ✓";
    color: green;
}

The heading displays a star before its text and a check mark after it. These symbols are generated by CSS and do not need to be written in the HTML heading itself.

Styling Selected Text

You can use ::selection to change the appearance of text when a user selects it.

::selection {
    background-color: blue;
    color: white;
}

Selected text receives a blue background and white text, subject to browser support and selection behavior.

Pseudo-Element vs. Pseudo-Class

A pseudo-element targets a specific part of an element or creates generated content, while a pseudo-class selects an element based on its state or position.

For example, p::first-letter styles the first letter of a paragraph, whereas a:hover styles a link when the pointer moves over it.

Learn more in our CSS Pseudo-Class Selectors and CSS Selectors tutorials.