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

Προωθημένο
Προωθημένο
Προωθημένο
Προωθημένο
Προωθημένο
Αναζήτηση
Προωθημένο
Virtuala FansOnly
CDN FREE
Cloud Convert
Κατηγορίες
Διαβάζω περισσότερα
Art
Hideo Kojima: KI wird für Spiele so wichtig sein wie der Sprung zu 3D
Kojima, KI, Spieleentwicklung, Cyberpunk 2077, Switch 2, PS6, Gaming-Trends, Technologie ##...
από Lena Nika 2025-08-30 11:05:27 1 417
Art
Recto: Falls Programmierung nicht schon schwierig genug ist
Programmierung, digitale Innovation, grafische Programmierung, Benutzeroberflächen,...
από Sara Lia 2025-08-17 18:05:31 1 271
Health
Top Benefits of Modern Knee Replacement Surgery
Knee pain is one of the most common problems that affects people as they age. Conditions such as...
από The Joint Clinic Dr Amite Pankaj 2025-09-08 10:39:05 0 311
άλλο
Moll FlexCut 760 Digital Rotary Die Cutter - B & R Moll - Moll Brothers
Rotary dies cutter for packaging - It is ideal for finishing boxes, cartons, labels, pocket...
από Shabirkhan 7sk 2025-02-20 07:29:37 0 396
Live Stream
Live streaming
Live media
από Drago Merkaš 2025-01-17 12:54:41 0 693
Προωθημένο
Virtuala FansOnly https://virtuala.site