replace content of img via css

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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?

回答1:

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.



回答2:

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


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