skip to Main Content

I tried to remove the broken icon in the img element when the destination url doesn’t exist, without deleting the img element :

HTML:

<img src="error.png">

CSS:

img {
  width: 100px;
  height: 100px;
  background-image: url(url.png);
  background-size: cover;
}

Instead of deleting the img element, I prefer to bring up the background-img without a broken icon.

I hope someone help me, I really need this.

2

Answers


  1. You can use ::before and ::after for this.

    Something like this:

    img {
      position: relative;
      width: 200px;
      height: 200px;
    }
    
    img::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-image: url(https://via.placeholder.com/200);
      background-size: cover;
    }
    <img src="wrong_link">
    <img src="https://via.placeholder.com/200">
    Login or Signup to reply.
  2. According to the answer I found on Stack Overflow, try using img:after in combination with the content property.
    How to hide image broken Icon using only CSS/HTML?

    img:after {  
      position: absolute;
      top: 0;
      left: 0;
      width: 100px;
      height: 100px;
      background-image: url(url.png);
      content: '';
    }
    

    Here you can find the working example: https://codepen.io/filipalbert/pen/QWZxPMp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search