Styling broken image alt-text with CSS

2.8k Views Asked by At

For my e-commerce site I'm using lazy loading for images with lazysizes. To provide conform img tags these contain an empty src="data:," suggest by this thread which is really neat.

So all lazy loaded images are display as a broken image with alt text until they reach view port. The problem is, that these alt texts contain product names which can be really long, so this text overflows image bounds sometimes and breaks layout (i.e. responsive):

enter image description here

Is there a cross-browser solution out there to style alt texts for images?

EDIT It's important to mention, that I'm talking about alt texts containing less to no whitespaces, so it would not line-break automatically.

2

There are 2 best solutions below

0
On BEST ANSWER

The solution is simple. Simply use word-break: break-word; on img tags

img {
  border: 3px solid red;
  max-width: 250px;
}
.wrap-broken {
  word-break: break-word;
}
<img alt="LLOYD Herren Businessschuh Don, Männer Schnürhalbschuhe,Halbschuh,Schnürschuh,Schnürer,Derby Schnürung,Anzugschuh,Office,Büro,REH/Stone,5.5 UK / 38.5 EU" src="https://www.kleiderliebe.de/herren/schuhe/anzugschuhe/lloyd-herren-businessschuh-don-maenner-schnuerhalbschuhe-halbschuh-schnuerschuh-schnuerer-derby-schnuerung.img">
<br><br>
<img class="wrap-broken" alt="LLOYD Herren Businessschuh Don, Männer Schnürhalbschuhe,Halbschuh,Schnürschuh,Schnürer,Derby Schnürung,Anzugschuh,Office,Büro,REH/Stone,5.5 UK / 38.5 EU" src="https://www.kleiderliebe.de/herren/schuhe/anzugschuhe/lloyd-herren-businessschuh-don-maenner-schnuerhalbschuhe-halbschuh-schnuerschuh-schnuerer-derby-schnuerung.img">

0
On

I don't believe there's any great CSS-only solution here. As others pointed out in the comments, a small amount of JS would go a long way here.

That said, here's some simple CSS which improves the appearance of the alt tag on missing images.

The key styles are the white-space: pre-wrap;, text-overflow: ellipsis;, and overflow: hidden;. The combo of these will automatically break long strings, add an ellipsis to long strings, and cut-off the alt text vertically.

img {
  display: inline-block;
  font-family: Arial;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: pre-wrap;
}
<img src="missing.jpg" width="200" height="100" alt="A really long description of an image that won't load">

<img src="missing.jpg" width="200" height="100" alt="An alt tag containing a URL - https://stackoverflow.com/questions/59434846/styling-broken-image-alt-text-with-css ">