- Home
- /
- Tutorials
- /
- CSS Tutorial
- /
- CSS Pseudo Elements
CSS Advanced Selectors
CSS Pseudo Elements
CSS Pseudo Elements are used to style specific parts of an HTML element.
Unlike pseudo classes, which target an element's state, pseudo elements target a particular portion of an element's content.
Pseudo elements begin with a double colon (::) and allow you to:
- Style the first letter
- Style the first line
- Insert content before or after an element
- Customize selected text
Common pseudo elements include:
- ::before
- ::after
- ::first-letter
- ::first-line
- ::selection
Syntax
CSS Pseudo Elements Syntax
css
selector::pseudo-element {
property: value;
}CSS Pseudo Elements Example
css
p::first-letter {
font-size: 32px;
}Makes the first letter of every paragraph larger.
Attributes
| Pseudo Element | Description | Example |
|---|---|---|
| ::before | Inserts content before an element | p::before |
| ::after | Inserts content after an element | p::after |
| ::first-letter | Styles the first letter | p::first-letter |
| ::first-line | Styles the first line | p::first-line |
| ::selection | Styles selected text | ::selection |
Example
CSS Pseudo Elements Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo Elements Example</title>
<style>
p::first-letter {
font-size: 36px;
color: red;
font-weight: bold;
}
p::first-line {
color: blue;
}
h2::before {
content: "★ ";
color: orange;
}
h2::after {
content: " ★";
color: orange;
}
::selection {
background-color: yellow;
color: black;
}
</style>
</head>
<body>
<h2>Featured Article</h2>
<p>
CSS pseudo elements allow developers to style specific parts of an element.
They are commonly used for decorative effects, typography, and dynamic content.
</p>
</body>
</html>Output
Browser Output
css
The first letter of the paragraph will appear large, bold, and red
The first line of the paragraph will appear blue
The heading will display orange stars before and after the text
Selected text will have a yellow backgroundBrowser Support
Chrome | Edge | Firefox | Safari | Opera | IE |
|---|---|---|---|---|---|
| Yes | Yes | Yes | Yes | Yes | Partial |
Notes
- Pseudo elements use a double colon (
::) in modern CSS. ::beforeand::afterrequire thecontentproperty.::first-letteris often used in magazine-style layouts.::selectionallows customization of highlighted text.- Pseudo elements do not modify the actual HTML content.
Common Pseudo Elements
| Pseudo Element | Purpose |
|---|---|
| ::before | Add content before an element |
| ::after | Add content after an element |
| ::first-letter | Style the first letter |
| ::first-line | Style the first line |
| ::selection | Style selected text |
Conclusion
CSS Pseudo Elements allow you to style specific portions of content and create decorative effects without modifying the HTML structure. They are powerful tools for enhancing typography, improving design, and adding visual details to web pages.
