Fix Broken Images with Only CSS

In web projects, images may sometimes fail to load due to various reasons. This can negatively impact the user experience. While it’s common to handle such cases using JavaScript, a simple CSS trick can also provide a quick and effective solution.

img {
  position: relative;
  width: 300px;
  height: 300px;
  margin-left:auto;
  margin-right:auto;
  object-fit: cover;
  display: block;
}

img:before {
  content: "The image could not be loaded.";
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  text-align: center;
  font-family: Arial;
  font-size:18px;
  color: red;
}

By controlling image loading with CSS, you can both improve page load speed and reduce the need for extra JavaScript.

Full example

Buy Me A Coffee

Explore More Posts