Sentinel: Your Web-Performance Watchman

Styling alt text on images

Written by on CSS Wizardry.

Table of Contents
  1. The code

I tweeted a tip the other day whereby you add text styles to images so that their alt text is differentiated if images, for whatever reason, cannot be loaded.

The tweet sparked more interest than I expected so I thought I would give the technique a more thorough writeup. The CSS is incredibly simple but it’s just one of those things that can make a lot of difference to someone’s UX.

The thinking is that by applying text-styles to images you can affect their alt text and how that appears if the image fails to load. This can help users realise there’s something different about a piece of content and that it’s perhaps not directly a part of the current text.

A lot of people weren’t aware this would or does work but if you think about it, any alt text you’ve ever seen will have been the same face, colour and style as the rest of the page. alt text (and therefore images) can be styled!

The code

I started doing this a long, long time ago but for some reason completely forgot about it until I started developing inuit.css.

I tend to always apply italics to the text and oftentimes a text colour. Italics is fairly failsafe as figures and asides etc are often set in italics.

Text colours can be more troublesome as it could be misconstrued as being a link, so use this wisely and avoid using the same colour as your links appear in.

Another fairly progressive (but potentially unstable) addition is to use the :after pseudo-element to append the text ‘(image)’ onto the alt text. This only seems to work in Firefox (4).

The code, in full, is simply:

img{
    font-style:italic;
    color:#c00;
}

/**
 * In Firefox we can insert the string ‘(image)’ into the alt text of an image that hasn’t loaded.
 */
img:after   { content:" (image)"; }
img::after  { content:" (image)"; } /* New CSS3 standard notation */

So there we have it, a simple, tiny addition to make your users’ experience a little more polished and complete…



Did this help? We can do way more!


Hi there, I’m Harry Roberts. I am an award-winning Consultant Web Performance Engineer, designer, developer, writer, and speaker from the UK. I write, Tweet, speak, and share code about measuring and improving site-speed. You should hire me.

You can now find me on Mastodon.


Suffering? Fix It Fast!

Projects

  • inuitcss
  • ITCSS – coming soon…
  • CSS Guidelines

Next Appearance

  • Talk & Workshop

    WebExpo: Prague (Czech Republic), May 2024

Learn:

I am available for hire to consult, advise, and develop with passionate product teams across the globe.

I specialise in large, product-based projects where performance, scalability, and maintainability are paramount.