Skip to main content

Pseudo-elements in CSS (Live Playground)

Pseudo-elements in CSS allow you to target and style specific parts of HTML elements, such as the first letter or line of text within an element, or to generate content before or after an element. In this tutorial, you will learn how to use pseudo-elements effectively, along with sample code and simple explanations.

Using pseudo-elements

To use a pseudo-element, write two colons followed by the pseudo-element name after the selector. The styles within the declaration block will be applied to the specified part of the element.

Example:

CSS
/* Style the first letter of a paragraph */
p::first-letter {
font-size: 2em;
font-weight: bold;
}
HTML
<p>This paragraph has a large, bold first letter.</p>

In this example, the pseudo-element p::first-letter targets the first letter of a paragraph and applies the specified font-size and font-weight styles.

Live Playground, Try it Yourself

Generating content with pseudo-elements

Pseudo-elements can also be used to generate content before or after an element. To do this, use the content property within the declaration block.

Example:

CSS
/* Add a quotation mark before a blockquote element */
blockquote::before {
content: '“';
font-size: 2em;
}

/* Add a quotation mark after a blockquote element */
blockquote::after {
content: '”';
font-size: 2em;
}
HTML
<blockquote>This is a quote with large quotation marks.</blockquote>

In this example, the pseudo-elements blockquote::before and blockquote::after generate content before and after the blockquote element, adding large quotation marks.

Live Playground, Try it Yourself

Other pseudo-elements

CSS provides several other pseudo-elements to help you target specific parts of elements or create custom styles. Some of these include:

  • ::first-line: Targets the first line of a block-level element
  • ::selection: Targets the text selected by the user
  • ::marker: Targets the marker box of a list item

Example:

CSS
/* Style the first line of a paragraph */
p::first-line {
font-weight: bold;
color: darkblue;
}

/* Style the selected text */
::selection {
background-color: lightblue;
color: darkblue;
}

/* Style the marker of a list item */
li::marker {
color: red;
}
HTML
<p>This paragraph has a bold, dark blue first line.</p>
<p>Select some text in this paragraph to see the custom selection style.</p>
<ul>
<li>Red marker for this list item</li>
<li>Red marker for this list item too</li>
</ul>
Live Playground, Try it Yourself

Conclusion

In this tutorial, you learned how to use pseudo-elements in CSS to target specific parts of HTML elements and to generate content before or after elements. With this knowledge, you can create unique and custom styles for your web page, enhancing the overall design and user experience.