Saturday, May 2, 2020

covering up broken images in CSS

For COVID reasons, Somerville PorchFest is Somerville CouchFest this year. Organizers are encouraging participating musicians to signup to do live streams and premiere videos and the like.

You can view my current draft of the day-of design.

Some bands are missing images, and so I hunted down a way of replacing the usual gangly "broken image" bit with something more deliberate looking...

the trick seems to be that broken images will be subject to the ::before pseudo-selector but loaded images won't be, so we can jam in some content... something like

.band img {
    position: relative;
    display: inline-block;
    vertical-align: text-bottom;
}

.band img::before {
    content: 'missing:' attr(alt);
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    line-height: 20px;
    background-color: #ccc;
    text-align: center;
    display: block;
    width: 280px;
    height: 280px;
    overflow: hidden;
}

That's assuming you have meaningful alt tags, otherwise you can just leave it blank.

This page has a deeper look.

I decided to stick with Vanilla.js... or at least the ES6 flavor of it.

UPDATE: I don't have time to mess with this now, but it looks like maybe this trick doesn't work in Firefox. Better just to use a tiny bit of javascript, in my case:
<img src='${photo}' onError="replaceImageWithPlaceholder(this)">
and
function replaceImageWithPlaceholder(what) {
    what.src = 'porchfestweb12.png';
}



I feel guilty for not turning it into a practice exercise in React or Vue, but after one person interviewing me mentioned he didn't like JSX, that templates were simpler... well, I don't agree, I think JSX are pretty elegant and simple once you get the build system setup, but man... in the meanwhile the backtick quotes and templating really pull the load that used to be carried by JQuery Handlebars. This page is pretty static, but the idea of replacing all the content of a container with something made from data is pretty dang easy to implement with that quoting and array built-ins such as map and filter...

No comments:

Post a Comment