You can style alt text like any other text

0
638

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

Sponsor
Sponsor
Sponsor
Sponsor
Sponsor
Zoeken
Sponsor
Virtuala FansOnly
CDN FREE
Cloud Convert
Categorieën
Read More
Other
Simplify Your NURS FPX 6426 Journey with Expert Academic Support
Simplify Your NURS FPX 6426 Journey with Expert Academic Support   Online nursing...
By Kenneth Nelson 2025-06-26 13:25:50 0 1K
Art
Wie die Widget-Revolution das Dosenbier revolutionierte
## Ein neuer Stern am Bierhimmel: Das Widget Stellen Sie sich vor, Sie betreten eine gemütliche...
By Lara Josefine 2025-08-14 12:05:31 1 761
Other
Genealogy Products & Services Market Size, Share, and Global Trends
Market Overview and Summary The global genealogy products and services market is witnessing...
By MAYUR YADAV 2025-09-10 10:25:34 0 567
Art
كيفية انتشار المعلومات المضللة حول حادث إطلاق النار في مينيسوتا كالنار في الهشيم
المعلومات المضللة، إيلون ماسك، حادث إطلاق النار، منصة X، الأخبار العاجلة، وسائل التواصل...
By هشام أنس 2025-09-06 10:05:28 1 1K
Sponsor
Virtuala FansOnly https://virtuala.site