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

Sponsorizzato
Sponsorizzato
Sponsorizzato
Sponsorizzato
Sponsorizzato
Cerca
Sponsorizzato
Virtuala FansOnly
CDN FREE
Cloud Convert
Categorie
Leggi tutto
Art
Destiny 2: Der Zorn über die Unreal Engine Demos
Destiny 2, Unreal Engine, Sava Zivkovic, AAA-Spiele, Axis Studios, Animation, VFX, GameDay ##...
By Sofia Dina 2025-08-22 02:05:17 1 204
Crafts
How to Watch Nationals vs. Reds TV Channel Live Stream - July 21
and the Washington Nationals will take the field against the Cincinnati Reds and on Sunday at...
By Verna Skiles 2025-10-27 03:41:02 0 125
Art
Come Pulire il Tuo Materasso (2025)
## Introduzione Se pensi che il tuo materasso sia un semplice oggetto su cui dormire, ti sbagli...
By Teresa Nicole 2025-08-04 01:05:46 1 375
Altre informazioni
Nevjerojatni prizori, Kim snimljen na bazenu: Pazite tek što se nalazi na stoliću pored
Nevjerojatni prizori, Kim snimljen na bazenu: Pazite tek što se nalazi na stoliću pored...
By Vedrana Kašić 2025-06-26 12:56:10 0 236
Literature
NURS FPX 4055 Assessment 4: Health Promotion Plan
As healthcare continues to evolve, nurses are taking on increasingly complex...
By Amelia Harper 2025-07-02 09:57:33 0 440
Sponsorizzato
Virtuala FansOnly https://virtuala.site