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

Sponsored
Sponsored
Sponsored
Sponsored
Sponsored
Search
Sponsored
Virtuala FansOnly
CDN FREE
Cloud Convert
Categories
Read More
Games
The Emotional Heart of FC 26 Ultimate Team Coins
In the dynamic universe of EA Sports FC 26, FC 26 Ultimate Team Coins are a vital resource...
By Claus Oliver 2025-09-25 03:43:23 0 1K
Health
Finding the Best Gastroenterologist in Ranchi: An Informational Guide
  Digestive health is a vital part of overall well-being, yet it is often overlooked...
By Dr Chandan Kumar Yadav 2025-09-09 11:24:53 0 1K
Other
NordVPN Winter Sales: Step into the Limitless World of Streaming
NordVPN, winter sales, online security, streaming services, VPN discounts, unlimited access,...
By Lina Frida 2026-01-11 04:05:22 0 379
Art
### A Tristeza das Impressões 3D: O Processo de Acabamento com Bondo
impressões 3D, Bondo, putty, acabamentos, suavização, apresentação, lamento, tristeza, arte,...
By Fernando Manuel 2025-08-31 09:05:31 1 679
Food
Agarwood Essential Oil Market Size, Share & Trends Analysis – Insights Report 2024-2032
Agarwood Essential Oil Market Overview: Agarwood is one of the essential oils in the department,...
By Cassie Tyler 2024-11-18 06:38:59 0 1K
Sponsored
Virtuala FansOnly https://virtuala.site