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 🤷‍♂️.

Sponzorováno
Sponzorováno
Sponzorováno
Sponzorováno
Sponzorováno
Hledat
Sponzorováno
Virtuala FansOnly
CDN FREE
Cloud Convert
Kategorie
Číst více
Ostatní
Prime Day : Les offres jeux vidéo à ne surtout pas manquer chez Amazon jusqu'au 11 juillet
Prime Day : Les offres jeux vidéo à ne surtout pas manquer chez Amazon jusqu'au 11 juillet...
Od Mary Fourth 2025-07-08 15:55:52 0 291
Art
Bruce Weber: Modada Erkekliği Yeniden Tanımlayan Fotoğrafçı
## Giriş Bruce Weber, modanın geçmişinde bir dönüm noktası olarak kabul edilen bir isimdir....
Od Matko Tuna 2025-08-07 04:05:18 1 247
Art
Atualização IOS 18.6.1 da Apple: Vale a Pena Baixar?
atualização IOS, Apple, IOS 18.6.1, vale a pena, download IOS ## Introdução A Apple lançou...
Od Liz Mónica 2025-08-17 03:05:15 1 272
Art
ماذا يعني رمز الشخص بجوار الوقت على الآيفون؟
شخص, آيفون, رمز الشخص, وقت, تكنولوجيا, معلومات, هاتف ذكي, استخدام الآيفون, ميزات الآيفون ##...
Od Can Baran 2025-08-15 15:05:24 1 158
Ostatní
Izrael se priprema za novi udar:Bit će teški dani,Iran u pripravnosti,ovo je objava rata a evo što na sve kaže Trump
Izrael se priprema za novi udar: 'Bit će teški dani'; Iran u pripravnosti: 'Ovo je objava...
Od Drago Merkaš 2025-06-13 15:15:05 0 510
Sponzorováno
Virtuala FansOnly https://virtuala.site