You can style alt text like any other text

0
318

You can style alt text like any other text | CSS-Tricks

Clever, clever that Andy Bell. He shares a technique for displaying image alt text when the image fails to load. Well, more precisely, it’s a technique to apply styles to the alt when the image doesn’t load, offering a nice UI fallback for what would otherwise be a busted-looking error.

The recipe? First, make sure you’re using alt in the HTML. Then, a little JavaScript snippet that detects when an image fails to load:

const images = document.querySelectorAll("img");

if (images) {
  images.forEach((image) => {
    image.onerror = () => {
      image.setAttribute("data-img-loading-error", "");
    };
  });
}

That slaps an attribute on the image — data-img-loading-error — that is selected in CSS:

img[data-img-loading-error] {
  --img-border-style: 0.25em solid
    color-mix(in srgb, currentColor, transparent 75%);
  --img-border-space: 1em;

  border-inline-start: var(--img-border-style);
  border-block-end: var(--img-border-style);
  padding-inline-start: var(--img-border-space);
  padding-block: var(--img-border-space);
  max-width: 42ch;
  margin-inline: auto;
}

And what you get is a lovely little presentation of the alt that looks a bit like a blockquote and is is only displayed when needed.

Andy does note, however, that Safari does not render alt text if it goes beyond a single line, which 🤷‍♂️.

Patrocinado
Patrocinado
Patrocinado
Patrocinado
Patrocinado
Pesquisar
Patrocinado
Virtuala FansOnly
CDN FREE
Cloud Convert
Categorias
Leia Mais
Art
Test Wheel World: O Mundo Aberto que Valoriza a Bicicleta
mundo aberto, Test Wheel World, Messhof, jogos de bicicleta, ActuGaming.net, videogames,...
Por Liz Mónica 2025-08-17 15:05:21 1 443
Art
In 'Alien: Earth' ist die Zukunft eine Unternehmenshölle
Alien, Zukunft, Unternehmenshölle, Noah Hawley, dystopischer Kapitalismus, moralischer Horror,...
Por Katharina Leonie 2025-08-13 22:05:19 1 411
Art
Tencent Revoluciona a Criação de Jogos com a VISVISE: Da Arte à Agonia em Minutos
tencent, ai, criação de jogos, VISVISE, produção de arte, ferramentas de jogo, tecnologia de...
Por Diego Bruno 2025-08-23 05:05:23 1 340
Art
Multi-Use-Dach Beseitigt Dachprobleme
Solarenergie, Dachwartung, Mehrzweckdach, Solarpanel Installation, Dachstruktur, Nachhaltige...
Por Mia Sara 2025-09-11 16:05:20 1 477
Art
ZOE Begone! – Der Wahnsinn eines nostalgischen Retro-Spiels
ZOE, Retro-Spiel, Handzeichnungen, künstlerischer Feind, Gaming-Chaos, Indie-Spiele ##...
Por Sophie Leni 2025-08-12 14:05:23 1 215
Patrocinado
Virtuala FansOnly https://virtuala.site