Pseudo-elements allow you to style specific parts of an element or insert content without changing the HTML. The most commonly used pseudo-elements are ::before and ::after.
What are ::before and ::after
::before inserts content before the actual content of an element.
::after inserts content after the actual content of an element.
These are useful for adding decorative elements, icons, labels, or effects without extra HTML tags.
Basic Syntax
selector::before {
content: “Text or empty”;
}
selector::after {
content: “Text or empty”;
}
The content property is required. Without it, the pseudo-element will not appear.
Example 1 Adding Text
p::before {
content: “Note: “;
color: red;
}
This will automatically add the word “Note:” before every paragraph.
Example 2 Decorative Styling
h2::after {
content: “”;
display: block;
width: 50px;
height: 3px;
background-color: black;
}
This creates a line below each heading without adding extra HTML.
Example 3 Button Hover Effect
button::after {
content: ” →”;
}
button:hover::after {
color: blue;
}
This adds an arrow after the button text and changes color on hover.
Example 4 Using Icons
li::before {
content: “✔ “;
color: green;
}
This adds a check icon before each list item.
Positioning Pseudo-elements
You can position pseudo-elements using CSS positioning.
div {
position: relative;
}
div::before {
content: “”;
position: absolute;
top: 0;
left: 0;
}
This allows you to place elements exactly where needed.
Important Notes
Pseudo-elements do not work on all HTML elements such as input fields.
They are mainly used for styling and decoration, not important content.
Always use content property even if it is empty.
They help keep HTML clean and reduce extra tags.
Practice Task
Create a card design where
A label appears before the title using ::before
A decorative line appears after the title using ::after