Inputting a default image in case the src attribute of an html

后端 未结 22 2463
渐次进展
渐次进展 2020-11-22 16:02

Is there any way to render a default image in an HTML tag, in case the src attribute is invalid (using only HTML)? If not, what would

22条回答
  •  深忆病人
    2020-11-22 16:38

    An HTML only solution, where the only requirement is that you know the size of the image that you're inserting. Will not work for transparent images, as it uses background-image as a filler.

    We can successfully use background-image to link the image that appears if the given image is missing. Then the only problem is the broken icon image - we can remove it by inserting a very big empty character, thus pushing the content outside the display of img.

    img {
      background-image: url("http://placehold.it/200x200");
      overflow: hidden;
    }
    
    img:before {
      content: " ";
      font-size: 1000px;
    }
    This image is missing:
    
    And is displaying the placeholder


    An CSS only solution (Webkit only)

    img:before {
      content: " ";
      font-size: 1000px;
      background-image: url("http://placehold.it/200x200");
      display: block;
      width: 200px;
      height: 200px;
      position: relative;
      z-index: 0;
      margin-bottom: -16px;
    }
    This image is there:
    
    This image is missing:
    And is displaying the placeholder

提交回复
热议问题