Code Red Digital Ltd

Using alt text for images inserted with CSS content property

It is quite common to use the content CSS propety to add an image using the ::before or ::after psuedo elements.

h1::before {
  content: url("my-logo.png");
}

This does not add Alternate text to the image, this feature has been supported in Chromium and Webkit browsers for a while and is coming to Firefox in version 128.

Alt text syntax

After the url() function add slash followed by a string in quotes.

h1::before {
  content: url("my-logo.png") / "My Alt Text ";
}

If using ::before add whitespace at the end of the string and if using ::after before the string.

Unfortunately in versions prior to 128 will break the content as it can't parse and the image will not display.

Checking for support

The first option is to declare the property twice the first without alt text and secondly with if supported the second one will be used if not the first will as the second one won't be abale to be parsed

h1::before {
  content: url("my-logo.png");
  content: url("my-logo.png") / "My Alt Text "; /* only used if parsed */
}
The second option is to use the @supports CSS at-rule.
h1::before {
  content: url("my-logo.png");
}
@supports (content: url("my-logo.png") / "My Alt Text ") {
  a::before {
    content: url("my-logo.png") / "My Alt Text ";
  }
}

Current browser support .

Finding the Alt Text

As the content does not live in the HTML and is added via the CSS content property then you need to do some digging, and this is different in different browsers.

Firefox

In firefox right click on the inserted image > select Inspect Accessibility Properties .

Chrome

In chrome right click on the inserted image > select Inspect and switch to the Accessibility panel .

Safari

In safari make show Developer Tools is enabled:
Safari > Settings > Advanced and checking the Show Develop menu in menu bar checkbox

Right click on the inserted image > select Inspect , in the Elements panel > click Node and select Accessibility .