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.
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.
/* Style the first letter of a paragraph */
<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.
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.
/* Add a quotation mark before a blockquote element */
/* Add a quotation mark after a blockquote element */
<blockquote>This is a quote with large quotation marks.</blockquote>
In this example, the pseudo-elements
blockquote::after generate content before and after the blockquote element, adding large quotation marks.
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
/* Style the first line of a paragraph */
/* Style the selected text */
/* Style the marker of a list item */
<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>
<li>Red marker for this list item</li>
<li>Red marker for this list item too</li>
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.