6

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?

Danield
  • 121,619
  • 37
  • 226
  • 255
eyal halperin
  • 111
  • 4
  • 11

2 Answers2

9

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

enter image description here

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)

enter image description here

Now change the pink background to your new background

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

and you're done.

Danield
  • 121,619
  • 37
  • 226
  • 255
  • Wow, very nice trick. You may set only `width` (but not `height`) to `0` and set padding to `0 50%`. Then it will work for any image size. – kirilloid Aug 28 '13 at 10:27
-1

HTML

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

CSS

img{
  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://lorempixel.com/200/200) no-repeat;
  width: 200px; /* Width of new image */
  height: 200px; /* Height of new image */
  padding-left: 200px; /* Equal to width of new image */
  }
Yuvaraj P
  • 2,067
  • 3
  • 15
  • 12