02. Pseudo-elements (::before, ::after, ::placeholder, ::marker)

🟡 Intermediate

1. Definition

A Pseudo-element (::selector) styles specific parts of an element: inserting decorative content without extra HTML (::before, ::after requiring content: ""), styling input hints (::placeholder), list bullets (::marker), or custom file inputs (::file-selector-button).

2. Why It Is Used

Pseudo-elements eliminate DOM bloat by generating visual accent icons, custom list bullets, and tooltips purely via CSS without cluttering HTML markup.

3. How It Works

::before inserts a virtual child element before the element's content; ::after inserts a virtual child after. Both require a declared content: "" property to render.

4. Syntax

.required-label::after {
  content: " *";
  color: #ef4444;
}

5. Pseudo-elements Reference Table

Pseudo-elementRequires content?Target Description
::beforeYes (Mandatory)Inserts virtual element before content
::afterYes (Mandatory)Inserts virtual element after content
::placeholderNoStyles input placeholder text hint
::markerNoStyles list item bullets or numbers
::selectionNoStyles user mouse text selection highlight

6. Beginner Example

::selection {
  background-color: #38bdf8;
  color: #0f172a;
}

7. Intermediate Example

input::placeholder {
  color: #94a3b8;
  font-style: italic;
}

8. Advanced Tooltip Overlay Example

.tooltip {
  position: relative;
}

.tooltip::after {
  content: attr(data-tooltip);
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: #0f172a;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  white-space: nowrap;
}

9. Line-by-Line Code Explanation

  • content: attr(data-tooltip);: Dynamically fetches the string stored inside HTML attribute data-tooltip="..." and renders it as content inside ::after.

10. Expected Terminal / Browser Output

A CSS tooltip badge appearing above interactive elements when hovered.

11. Common Mistakes & Pitfalls

  • Forgetting content: "" on ::before or ::after: Omitting content prevents the pseudo-element from rendering completely.

12. Important Rules & Limitations

  • Pseudo-elements cannot be applied to self-closing replaced elements like <img> or <input>.

13. Multilingual Explanation: English

Pseudo-elements (::before and ::after) insert decorative virtual content without altering HTML structure.

14. Multilingual Explanation: Hindi (Roman Script)

::before aur ::after bina HTML change kiye decorative designs aur icons insert karne ke kaam aate hain.

15. Multilingual Explanation: Marathi (Roman Script)

::before ani ::after mule extra HTML n lihita decorative content insert karta yete.

16. Practice Questions

  1. Why does ::before fail to render if content is not declared?

17. Practical Coding Challenge

Create a .badge-new::after rule that appends a green `" NEW"` tag after link titles.

18. Related Topics