Pseudo-classes and Pseudo-elements
30 minPseudo-classes and Pseudo-elements allow you to style elements based on their state or specific parts of their content, without adding extra classes or HTML markup. They are powerful tools for keeping your HTML clean.
**Pseudo-classes** start with a single colon (`:`) and select elements based on state (e.g., `:hover`, `:focus`, `:checked`) or position (e.g., `:first-child`, `:nth-child`). They answer the question 'What is the element doing?' or 'Where is it?'.
**Pseudo-elements** start with double colons (`::`) and allow you to style specific parts of an element (e.g., `::first-letter`, `::placeholder`) or insert virtual content (e.g., `::before`, `::after`). They answer the question 'What part of the element?'
The `::before` and `::after` pseudo-elements are particularly versatile. By setting their `content` property (even to an empty string), you can create decorative shapes, icons, or overlays purely with CSS.
Key Concepts
- Pseudo-classes (`:`) target state or position.
- Pseudo-elements (`::`) target parts or insert content.
- `:hover`, `:focus`, `:active` are user-action states.
- `::before` and `::after` create virtual elements.
- The `content` property is required for pseudo-elements.
Learning Objectives
Master
- Differentiating between pseudo-classes and pseudo-elements
- Styling interactive states (links, inputs)
- Using structural pseudo-classes (:nth-child)
- Creating decorative elements with ::before/::after
Develop
- Writing semantic, clean HTML
- Creative problem solving with CSS-only solutions
- Enhancing accessibility with focus styles
Tips
- Always define `:focus` styles for accessibility.
- Use `::before` and `::after` for cosmetic additions to keep HTML semantic.
- Remember the 'LVHA' order for links: Link, Visited, Hover, Active.
- Use single colon `:` for pseudo-elements only if you need IE8 support (rare).
Common Pitfalls
- Forgetting the `content: '';` property on `::before`/`::after` (nothing will show).
- Confusing `:nth-child` (counts all siblings) with `:nth-of-type` (counts same tag).
- Removing outline on `:focus` without providing an alternative (bad for accessibility).
- Trying to attach pseudo-elements to self-closing tags like `<img>` or `<input>` (doesn't work).
Summary
- Pseudo-classes target states (hover, focus).
- Pseudo-elements target parts (first-line, before).
- They reduce the need for extra HTML classes.
- Essential for interactivity and decoration.
Exercise
Use the `::before` pseudo-element to add a '➤ ' symbol before every list item.
li::before {
content: "➤ ";
color: green;
}
Exercise Tips
- Try using ::after to add content after elements.
- Use ::first-letter to style the first letter of a paragraph.
- Combine pseudo-classes with pseudo-elements: li:hover::before.
- Experiment with content: url('image.png') to add images via CSS.