With CSS pseudo-elements, you can style elements or parts of elements without needing to assign them IDs or classes. This comes in handy when you want to style specific elements, like the first letter of a paragraph for a decorative effect, or add content before or after an element, all through your style sheet.
CSS3 introduced a new syntax for pseudo-elements using double colons (::) to differentiate them from pseudo-classes. Here's how you can define the new syntax for a pseudo-element:
Here are some commonly used pseudo-elements:
The ::first-line pseudo-element allows you to apply special styling to the first line of text within an element.
In the following example, the style rules format the first line of text within a paragraph. The length of the first line depends on the size of the browser window or the containing element.
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
Note: You can apply various CSS properties to the ::first-line pseudo-element, including font properties, background properties, color, word spacing, letter spacing, text decoration, vertical alignment, text transformation, and line height.
The ::first-letter pseudo-element allows you to style the first letter of the first line of text within an element in a unique way, often used to create a drop cap effect.
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
Note: Various CSS properties can be applied to the ::first-letter pseudo-element, including font properties, text decoration, text transformation, letter spacing, word spacing, line height, float, vertical alignment (only if 'float' is 'none'), color, margin and padding properties, border properties, and background properties.
The ::before and ::after pseudo-elements allow you to insert generated content either before or after an element's content. You can use the 'content' CSS property along with these pseudo-elements to insert the generated content.
This is particularly useful for enhancing an element with additional content that isn't part of the actual markup of the page. You can insert regular text strings or embedded objects like images and other resources using these pseudo-elements.
h1::before {
content: url("images/marker-left.gif");
}
h1::after {
content: url("images/marker-right.gif");
}
Often, you'll want to style only specific paragraphs of text or other block-level elements using pseudo-elements. This is where applying a class to the pseudo-element becomes useful. By combining pseudo-elements with CSS classes, you can achieve effects specifically for elements with that class.
In the following example, the style rules will display the first letter of all paragraphs with the class "article" in green and a font size of xx-large.
p.article::first-letter {
color: #00ff00;
font-size: xx-large;
}