Pseudo-Elements in CSS
- Siddharth Sharma
- Mar 3, 2025
- 2 min read
Pseudo-elements in CSS are used to style specific parts of an element. They allow you to insert content before or after an element, style the first letter or line of an element, and more. Pseudo-elements are denoted by a double colon (::), though a single colon (:) is also supported for backward compatibility.
Common Pseudo-Elements
::before
Inserts content before the content of an element.
Example:
css
p::before {
content: "Note: ";
font-weight: bold;
color: red;
}
This will add "Note: " before every <p> element.
::after
Inserts content after the content of an element.
Example:
css
p::after {
content: " - Read more";
font-style: italic;
color: blue;
}
This will add " - Read more" after every <p> element.
::first-letter
Styles the first letter of an element.
Example:
css
p::first-letter {
font-size: 2em;
font-weight: bold;
color: green;
}
This will make the first letter of every <p> element larger and bold.
::first-line
Styles the first line of an element.
Example:
css
p::first-line {
font-weight: bold;
color: purple;
}
This will make the first line of every <p> element bold and purple.
::selection
Styles the portion of an element that is highlighted by the user.
Example:
css
::selection {
background-color: yellow;
color: black;
}
This will change the highlight color to yellow and text color to black.
Key Points to Remember
content Property: Required for ::before and ::after pseudo-elements to display content.
Inline by Default: Pseudo-elements are inline by default, but you can change their display property.
Combining Pseudo-Elements: You can combine pseudo-elements with classes or IDs for more specific targeting.
css
.special::before {
content: "⭐";
}
Example: Combining Pseudo-Elements
html
<p class="quote">This is a motivational quote.</p>
css
.quote::before {
content: "“";
font-size: 2em;
color: orange;
}
.quote::after {
content: "”";
font-size: 2em;
color: orange;
}
.quote::first-letter {
font-size: 1.5em;
font-weight: bold;
color: navy;
}
.quote::first-line {
font-style: italic;
}
Result:
The text will be wrapped in orange quotation marks.
The first letter will be larger and bold.
The first line will be italicized.
Pseudo-elements are powerful tools for enhancing the design and functionality of web pages without adding extra HTML markup.




Comments