Using :before and :after CSS selector to insert HTML
⚡TLDR
Add decorative text/icons with CSS :before and :after. Use the content property to insert content *visually not structurally:
This makes visual quotes around text, but they're purely cosmetic—they're excluded from the DOM, making them inaccessible to search engines and screen readers.
Lack of HTML insertion support
Though :before and :after contribute to visual presentation, they don't support HTML tags:
- They insert strings of text or CSS entities, but not HTML.
- Their content is off-limits to screen readers or search engines.
- They're incapable of creating interactive elements such as buttons or links.
Inserting HTML: A workaround
For dynamic HTML content insertion, rely on JavaScript or jQuery:
This allows for interactive HTML elements to be inserted around a selected element.
How to escape characters in content
Avoid syntax errors by correctly escaping quotes when using the content property:
Using single quotes around the property value makes it simpler to include double quotes in the content.
:before and :after use cases
- Adding decorative items, like quotes (“and”) or bullets (•).
- Styling numbers for ordered lists (e.g., 01.,02.).
- Inserting icons (resourceful when working with icon libraries like Font Awesome).
Linked
Linked
Was this article helpful?
