You can style alt text like any other text

0
273

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

Спонсоры
Спонсоры
Спонсоры
Поиск
Virtualbook
CDN FREE
Категории
Больше
Art
AI hat ein Branding-Problem: Wir verdienen mehr als nur ein Textfeld und ein paar Toggle-Schalter
AI, Branding, Technologie, Benutzererfahrung, Innovation, digitale Transformation, KI,...
От Lorena Ella 2025-08-23 13:05:23 1 55
Art
Crimson Desert: Ein neuer Verzögerungsschock – Release erst im ersten Quartal 2026
Crimson Desert, Verzögerung, Spiele, Gaming-News, 2026, Entwickler, Videospiele, Release,...
От Lara Anna 2025-08-13 06:05:31 1 33
Другое
AI Integration and 3D Imaging Advancing the CT Scanner Industry
Polaris Market Research presents a comprehensive evaluation of the CT Scanner Market., with a...
От MAYUR YADAV 2025-09-01 13:57:46 0 15
Art
Top jeux érotiques sur Steam : attention, vous risquez de devenir accro !
jeux érotiques, Steam, jeux vidéo, addiction, réalité virtuelle, stimulation des sens,...
От Laure Olivia 2025-08-28 22:05:32 1 31
Другое
Confectionery Fillings Market to touch USD 2,605.60 million at 5.58% CAGR by 2030
The confectionery fillings market has experienced significant growth in recent years, driven by...
От Cassie Tyler 2025-01-29 05:54:36 0 349
Спонсоры
Virtuala FansOnly https://virtuala.site