You can style alt text like any other text

0
317

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

إعلان مُمول
إعلان مُمول
إعلان مُمول
إعلان مُمول
إعلان مُمول
البحث
إعلان مُمول
Virtuala FansOnly
CDN FREE
Cloud Convert
الأقسام
إقرأ المزيد
Art
Marvel Tōkon: Fighting Souls Beta Oyun Zamanları Bu Hafta Sonu
Marvel, Tōkon: Fighting Souls'un beta sürümünü bu hafta sonu oyunculara sunuyor. Bu etkinlik,...
بواسطة Onur Sinan 2025-09-05 21:05:18 1 434
الرئيسية
Lunettes AR : une appli pour bloquer les pubs dans la vraie vie
Lunettes AR : une appli pour bloquer les pubs dans la vraie vie Envie d’un monde sans pubs...
بواسطة Mary Fourth 2025-06-29 09:07:58 0 265
Food
Food Antimicrobial Coating Market Trends, Size, and Share – Forecast to 2032
Food Antimicrobial Coating Market Overview: Significant concerns about cleanliness in various...
بواسطة Cassie Tyler 2024-12-06 09:57:30 0 469
Art
Así nació Schedule I, el videojuego desarrollado por una sola persona que arrasa con más de 2 millones de copias vendidas
## Introduzione Nel mondo dei videogiochi, ogni tanto emerge un titolo che sorprende tutti....
بواسطة Nicola Diego 2025-08-31 04:05:24 1 536
Food
Juice Concentrates Market: Size, Share, and Research Forecasts to 2030
Juice Concentrates Market – Overview: The demand for juice concentrates has increased...
بواسطة Cassie Tyler 2024-10-31 07:29:11 0 541
إعلان مُمول
Virtuala FansOnly https://virtuala.site