You can style alt text like any other text | CSS-Tricks
Briefly

Andy Bell introduces a technique that ensures image alt text is displayed through CSS styling when an image fails to load. The method involves using JavaScript to apply a custom data attribute when an error occurs, which then allows styling of the alt text to maintain a visually appealing layout. The article also notes a limitation with Safari, which does not render alt text that exceeds one line, indicating potential compatibility issues.
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; }
Andy does note, however, that Safari does not render alt text if it goes beyond a single line, which 🤷‍♂️.
Read at CSS-Tricks
[
|
]