Thursday, June 12, 2025
HomeProgrammingYou'll be able to fashion alt textual content like every other textual...

You’ll be able to fashion alt textual content like every other textual content


Intelligent, intelligent that Andy Bell. He shares a method for displaying picture alt textual content when the picture fails to load. Nicely, extra exactly, it’s a method to use kinds to the alt when the picture doesn’t load, providing a pleasant UI fallback for what would in any other case be a busted-looking error.

The recipe? First, be sure to’re utilizing alt within the HTML. Then, slightly JavaScript snippet that detects when a picture fails to load:

const pictures = doc.querySelectorAll("img");

if (pictures) {
  pictures.forEach((picture) => {
    picture.onerror = () => {
      picture.setAttribute("data-img-loading-error", "");
    };
  });
}

That slaps an attribute on the picture — data-img-loading-error — that’s chosen in CSS:

img[data-img-loading-error] {
  --img-border-style: 0.25em stable
    color-mix(in srgb, currentColor, clear 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 stunning little presentation of the alt that appears a bit like a blockquote and is is just displayed when wanted.

Andy does observe, nevertheless, that Safari doesn’t render alt textual content if it goes past a single line, which 🤷‍♂️.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments