Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Unavailable Images via CSS?

Tags:

Is it possible to replace the standard broken image via CSS or using another technique? All my images are the same size and my have transparency.

I've tried to wrap all images with a div's background:

<div class="no_broken">   <img src="http://www.web.com/found.gif"/> </div>  <div class="no_broken">   <img src="http://www.web.com/notfound.gif"/> </div> 

CSS:

div.no_broken {    background-image: url(standard.gif);  }  div.no_broken, div.no_broken img {    width: 32px;    height: 32px;    display: block;  } 

But this will display two images on top of each other if the IMG is transparent.

like image 530
aemkei Avatar asked Nov 04 '08 11:11

aemkei


People also ask

How do you swap an image in CSS?

Answer: Use the CSS background-image property You can simply use the CSS background-image property in combination with the :hover pseudo-class to replace or change the image on mouseover.

How do I fix an image in CSS?

To keep your background fixed, scroll, or local in CSS, we have to use the background-attachment property. Background-attachment: This property is used in CSS to set a background image as fixed or scroll. The default value of this property is scroll.

How do I change an image url in CSS?

You can't change it with CSS, you need Javascript for that. But if you are trying to change the image on for example hover, you could remove the img-tags and use a div instead on which you set a background-image. In your CSS you can then create a block where you change the image on hover.


2 Answers

This works without CSS:

<img src="some.jpg" onerror="this.src='alternative.jpg';"> 

It seems to even work when Javascript is disabled.

like image 81
schnaader Avatar answered Oct 01 '22 03:10

schnaader


Yes, you can replace an image with CSS, using a trick of pseudo selectors.

Basically, ::before and ::after only apply when the image fails to load. You can use absolute positioning to place the CSS pseudo element over the broken image placeholder:

img {      position: relative;      width: 200px;      height: 200px;      display: inline-block;      vertical-align: text-bottom;  }        img::before {          content: 'fall back';          position: absolute;          top: 0;          left: 0;          bottom: 0;          right: 0;          line-height: 200px;          background-color: #fd0;          color: currentColor;          text-align: center;          border-radius: 2px;          display: block;          width: 200px;          height: 200px;          overflow: hidden;      }
<img src="not-found">  <img src="https://via.placeholder.com/200">

This snippet works with no JS at all, but only works in newer browsers.

like image 27
Keith Avatar answered Oct 01 '22 04:10

Keith