CSS or Javascript - display fallback text if background image not loaded [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 13:07:32

Try it this way:

HTML

<div class="iHaveBgImage">
  <p>this text should be displayed if bg image is not loaded</p>
</div>

CSS

.iHaveBgImage { background-image:
url('https://s31.postimg.org/yqv51r5xn/6936671_hd_wallpapers_for_ipad.jpg');
color:red;
}

.iHaveBgImage > p {
  position: relative;
  z-index: -1;
}

Works perfectly https://jsfiddle.net/s0gt2eng/

Ani Menon

This is what I suggested in the duplicate tag:

.iHaveBgImage{
  width:500px;
  height:200px;
  background-image: url('http://www.menucool.com/slider/jsImgSlider/images/image-slider-5.jpg');
  }
<div class="iHaveBgImage" title="this text should be displayed if bg image is not loaded">
</div>

Alternative using span tags:

span.image:before{
  content:" "; background:url('http://www.menucool.com/slider/jsImgSlider/images/image-slider-5.jpg');
  display: block;
  position:absolute;
  width:500px;
  height:200px;
}
  <span class="image">alternate text</span>

One workaround to this would be to change

<div class="iHaveBgImage">
this text should be displayed if bg image is not loaded
</div>

.iHaveBgImage { background-image: url('img.png') }

To :

<img src="img.png" alt="Seems like this image failed to load" />

Alternatively I am not sure if the following would work, but you can MAYBE do something along the lines of:

<img class="iHaveBgImage" alt="Seems like this image failed to load" />

.iHaveBgImage { background-image: url('img.png') }

EDIT: Something that just popped up in my head that could possibly also work would be to have:

<div class="iHaveBgImage">
<p class="bgText">this text should be displayed if bg image is not loaded</p>
</div>

.iHaveBgImage { 
background-image: url('img.png') 
}
.bgText {
  z-index: -9999;
}

Try this

P.hidden {
    visibility: hidden;
}
.iHaveBgImage {
  background-image: url('https://s31.postimg.org/yqv51r5xn/6936671_hd_wallpapers_for_ipad.jpg');
  color: red;
width:700px;
  height:300px;
}
<div class="iHaveBgImage">
   <p class="hidden> This text should be displayed if bg image is not loaded</p>
</div>

if you want to use text visible to text use <span></span> tag and create css span {display: block;} or

html

 <p class="hidden> This text should be displayed if bg image is not loaded</p>

CSS

P.hidden {
    visibility: hidden;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!