Styling Alt Text as a Fallback UI
Andy Bell has shared a way to make broken images less ugly: style the alt text itself so it renders as a deliberate UI element when an image fails.
The starting point is the usual alt attribute in the HTML. From there, a JavaScript snippet watches for load failures:
const images = document.querySelectorAll("img");
if (images) {
images.forEach((image) => {
image.onerror = () => {
image.setAttribute("data-img-loading-error", "");
};
});
}
On failure it adds data-img-loading-error to the image, which CSS can then target:
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;
}
The result is the alt text presented in a blockquote-like style, appearing only when the fallback is actually needed.
One caveat from Bell: Safari won't render alt text that spills past a single line. 🤷♂️



