replace content of img via css

css, html, image

Solution

1) Set width and height of your image to 0.

2) Add a padding of 100px.

3) Add your new image via a background image

img {
  display: inline-block;
  background: url(http://lorempixel.com/200/200) no-repeat; /* <--- */
  width: 0; /* <--- */
  height: 0; /* <--- */
  padding: 100px; /* <--- */
}
.replace {
  display: inline-block;
  background: url(http://lorempixel.com/200/200) no-repeat;
  width: 0;
  height: 0;
  padding: 100px;
}
<h4>Image from placehold.it:</h4>

<img src="http://placehold.it/200x200"/>

<hr>

<h4>Same image in markup - but replaced via CSS</h4>

<img class="replace" src="http://placehold.it/200x200"/>

FIDDLE

How does this work?

Well, lets say we added padding to your original img element:

img {
    padding:100px;
    background: pink;
}

The result is your original img with 100px of pink background on each side

Now set width/height to 0:

img {
   padding:100px;
   background: pink;
   width:0;height:0;
}

You get a 200px X 200px pink area: (So now you've eliminated your original image)

Now change the pink background to your new background

background: url(http://lorempixel.com/200/200) no-repeat;

and you're done.

Problem

I have this image tag: ``` <img src="http://placehold.it/200x200"/> ``` I need to replace the image via css (because I can't edit the html),so I use this css: ``` img { content: url('http://lorempixel.com/200/200'); } ``` it's working well on chrome but not working in firefox and ie,any idea why?

Original source

Related problems