Explain Codes LogoExplain Codes Logo

Using :before and :after CSS selector to insert HTML

html
css-selectors
html-insertion
web-development
Nikita BarsukovbyNikita Barsukov·Dec 8, 2024
TLDR

Add decorative text/icons with CSS :before and :after. Use the content property to insert content *visually not structurally:

p:before { content: "“"; } /*Did somebody call for an opening quote? */ p:after { content: "”"; } /* And here's the closing quote! */

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:

let para = document.querySelector('p'); para.insertAdjacentHTML('beforebegin', '<div class="quote">“</div>'); /*Now, that's a fancy opening quote!*/ para.insertAdjacentHTML('afterend', '<div class="quote">”</div>'); /*And a classy closing quote to match!*/

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:

p:before { content: "\""; } /* Double quotes be like: "I've got your back, buddy!" */ p:before { content: "\'"; } /* Single quotes going: 'I'm small but mighty!' */

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).