Broken image custom styles

Broken image custom styles

by Csaba Hellinger

HTML

<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">
<div class="container">
  <img src="https://preview.redd.it/kjr580lc78j11.jpg?width=960&crop=smart&auto=webp&s=96a98dc8599a7fc3e48209e49c9269472aaf96fc" alt="Spring Doggo" />

  <img class="one" src="https://example.com/broken.png" alt="Spring Doggo" />

  <img class="two" src="https://example.com/broken.png" alt="Spring Doggo" />
</div>

<p>Two ways of giving custom style to broken images without JavaScript.</p>
<p>First: working image.</p>
<p>Second: fallback using SVG.</p>
<p>Third: fallback using FontAwesome icon and the alt text.</p>

<p>Of course it doesn't work in Safari</p>

CSS

body {
  background: #222;
  color: #ddd;
  font-family: FontAwesome, sans-serif;
}

.container {
  display: flex;
  gap: 1rem;
}

img {
  width: 200px;
  border-radius: 0.4rem;
  position: relative;
}

img:before {
  content: ' ';
  display: block;
  position: absolute;
  inset: 0;
}

img.one:after {
  content: "";
  display: block;
  position: absolute;
  inset: 0;
  background: url(https://upload.wikimedia.org/wikipedia/commons/6/65/No-Image-Placeholder.svg) center center / cover no-repeat;
}

img.two:after {
  content: "\f127"" Broken image of "attr(alt);
  display: flex;
  align-items: center;
  justify-items: center;
  text-align: center;
  position: absolute;
  inset: 0;
  font-size: 1.2rem;
  background-color: #333;
  color: #fff4;
}