What is a Pseudo Element in CSS: Simple Explanation and Examples
pseudo element in CSS lets you style parts of an element that don't exist in the HTML, like the first letter or content before/after an element. It uses special selectors like ::before and ::after to add or style these invisible parts without changing the HTML structure.How It Works
Think of a pseudo element as a way to add invisible helpers inside or around an HTML element without touching the actual HTML code. It's like adding decorations to a picture frame without changing the picture itself.
For example, you can style the first letter of a paragraph to be bigger or add some text before or after a heading using ::first-letter or ::before. These pseudo elements act like extra pieces that CSS creates on the fly to enhance the look.
This works by CSS selecting a part of the element or creating a virtual element, then applying styles to it. The browser shows these styles as if they were part of the original content, but they don't exist in the HTML source.
Example
This example shows how to add a red star before a heading using the ::before pseudo element.
h2::before {
content: "★ ";
color: red;
}
h2 {
font-family: Arial, sans-serif;
font-size: 1.5rem;
}When to Use
Use pseudo elements when you want to add decorative or functional styles without changing your HTML. For example:
- Adding icons or symbols before or after text.
- Styling the first letter or line of a paragraph for emphasis.
- Creating custom underlines or highlights.
- Inserting small visual effects like quotes or badges.
This keeps your HTML clean and separates content from design, making your code easier to maintain.
Key Points
- Pseudo elements let you style parts of elements that aren’t in the HTML.
- Common pseudo elements include
::before,::after, and::first-letter. - They help add decorative content without extra HTML tags.
- Use
contentproperty to insert text or symbols with::beforeand::after. - Pseudo elements improve design flexibility and keep HTML clean.