I need to replace the image via css (because I c...">

Replace img content with css

I have this image tag:

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

I need to replace the image via css (because I cannot edit html), so I use this css:

 img { content: url('http://lorempixel.com/200/200'); } 

It works well on chrome, but does not work in firefox, i.e. any idea why?

+6
source share
2 answers

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

2) Add a 100px add-on.

3) Add your new image through the 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 it works?

Well, let's say we added an add-on to your original img element:

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

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

enter image description here

Now set the width / height to 0:

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

You get a pink zone of 200px X 200px: (So, now you have excluded your original image)

enter image description here

Now change the pink background to a new background

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

and you're done.

+9
source

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 */ } 
-1
source

Source: https://habr.com/ru/post/952643/


All Articles