DEV Community

Salma Alam-Naylor
Salma Alam-Naylor

Posted on • Edited on • Originally published at whitep4nth3r.com

Hide text in CSS pseudo elements from screen readers with this one weird trick

Unfortunately this doesn't yet work in Safari or Firefox, but you can keep up to date with support on caniuse.com.

TL:DR; Add empty "alternative text" to the pseudo element content to prevent screen readers announcing your decorative design elements, like so:



.someClass::before {
  content: "M" / "";
}


Enter fullscreen mode Exit fullscreen mode

I'm currently redesigning my website, and part of the design includes decorative elements provided by a font, specified as single letters in the content of CSS pseudo elements. Psst! If you don't know what a CSS pseudo element is, read this post first:

Here's some code that adds a large stylised paint brush glyph as a pseudo element attached to the <main> HTML element of the page.



main::before {
  font-family: "Atomic Marker Extras";
  content: "M";
  position: fixed;
  z-index: -1;
  /* ... */
}


Enter fullscreen mode Exit fullscreen mode

When using VoiceOver for MacOS to read the page using that code, the letter M is announced. Not ideal! You can also confirm what will be announced using the Accessibility Tree view (enabled via an experimental flag in Chromium browsers), which gives you a visual display of all elements and their content that accessibility tools will have access to.

Browser accessibility tree view, showing a static text element with the content M as referenced in the code example above, that will be read out by screen readers.

Fortunately, the CSS content property comes with the ability to specify alternative text, which is especially useful if you're using images in your pseudo elements that actually mean something. And what's more, if you want to tell the browser that the content is purely decorative and doesn't need to be seen by assistive technology, you can provide an empty value for the alternative text, like so.



main::before {
 font-family: "Atomic Marker Extras";
 content: "M" / "";
 position: fixed;
 z-index: -1;
 /* ... */
}


Enter fullscreen mode Exit fullscreen mode

And that's it! One handy lesser-known feature of CSS to help you make your weird and wonderful website designs more enjoyable to browse, for everyone, everywhere.

Top comments (3)

Collapse
 
nickytonline profile image
Nick Taylor

TIL. Thanks for sharing Salma!

Collapse
 
anastasialanz profile image
Anastasia Lanz

Hi Salma! Thanks for the trick. I tried this out and it looks like adding the alternative text removes the ::before in Safari.

Collapse
 
whitep4nth3r profile image
Salma Alam-Naylor

You're right, this doesn't work in Safari and I meant to update the post 😅