DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com on

TIL: CSS "content" accepts alternative text

Developers often use before and after pseudo-elements (generated content) for the styling of elements in websites. With a few lines of extra CSS, it is possible to include icons, images, or even add text without adjusting the HTML.

Unfortunately, you have to consider using content in pseudo-elements very carefully because it can affect accessibility. Just because your generated content is not defined in the HTML, it doesn't mean that it is not picked up by assistive technology like screen readers.

Let's have a look at an example:

.new-item::before {
  content: "★";
}
Enter fullscreen mode Exit fullscreen mode

The above CSS code prepends the symbol (black star) to the inner content of elements with the class new-item. And this might be all great from a visual perspective, but for screen readers, it has unexpected side effects.

<a href="new-things">go to new things</a>
Enter fullscreen mode Exit fullscreen mode

This anchor link is now presented with the visual symbol of a star. On the other hand, screen readers will now read out "Black star go to new things". This experience is not great!

Today I learned that the content property supports a way to define alternative text for generated content.

.new-item::before {
  /* "black star" and element content is read out */
  content: "★";

  /* "Highlighted item" and element content is read out */
  content: "★" / "Highlighted item";

  /* Generated content is ignored and only element content is read out */
  content: "★" / "";
}
Enter fullscreen mode Exit fullscreen mode

That's pretty cool because we can now provide alternative texts right in CSS! Unfortunately, at the time of writing, the overall browser support is not given yet. Firefox (Bugzilla ticket) and Safari are missing.

Today, you should still use generated content, and this way of handling its alternative text very carefully. Going with a separate element in combination with aria-hidden=true is probably still a better approach these days.

Top comments (0)