css - pseudo-elements
CSS pseudo-elements allow you to style specific parts of an HTML element, such as the first line of a paragraph, the first letter of a block of text, or content that isn't in the HTML itself (like adding icons or decorative elements). These are a great way to enhance your designs without adding extra HTML elements.
This guide covers:
What are CSS Pseudo-elements?
Syntax of Pseudo-elements
Commonly Used Pseudo-elements
::before
::after
::first-line
::first-letter
::selection
::placeholder
::marker
Examples of Pseudo-elements in Action
Best Practices and Tips
1. What are CSS Pseudo-elements?
Pseudo-elements are used to style specific parts of an element, such as the first letter or line of a paragraph. Unlike pseudo-classes (which select elements based on their state), pseudo-elements allow you to create and style parts of elements that are not directly accessible in the HTML.
Example Syntax
selector::pseudo-element {
property: value;
}
Note: Pseudo-elements are written with two colons (::) to differentiate them from pseudo-classes (which use one colon :). However, for backward compatibility, older pseudo-elements like :before and :after can still be written with a single colon.
2. Syntax of Pseudo-elements
Example
p::first-line {
font-weight: bold;
color: blue;
}
This example styles only the first line of every <p> element, making it bold and blue.
3. Commonly Used Pseudo-elements
3.1 ::before
The ::before pseudo-element is used to insert content before an element's content. You can use it to add decorative icons, labels, or other visual elements.
<p>Welcome to my website!</p>
css
Copy code
p::before {
content: "