通过css替换img的内容

eya*_*rin 6 html css image css3

我有这个图片标签:

<img src="http://placehold.it/200x200"/>
Run Code Online (Sandbox Code Playgroud)

我需要通过css替换图像(因为我无法编辑html),所以我使用这个css:

img {
 content: url('http://lorempixel.com/200/200');
}
Run Code Online (Sandbox Code Playgroud)

它在chrome上工作得很好,但在firefox中没有工作,也就是说,任何想法为什么?

Dan*_*eld 9

1)将图像的宽度和高度设置为0.

2)添加100px的填充.

3)通过背景图像添加新图像

img {
  display: inline-block;
  background: url(http://lorempixel.com/200/200) no-repeat; /* <--- */
  width: 0; /* <--- */
  height: 0; /* <--- */
  padding: 100px; /* <--- */
}
Run Code Online (Sandbox Code Playgroud)

.replace {
  display: inline-block;
  background: url(http://lorempixel.com/200/200) no-repeat;
  width: 0;
  height: 0;
  padding: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<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"/>
Run Code Online (Sandbox Code Playgroud)

小提琴

这是如何运作的?

好吧,假设我们在原始的img元素中添加了填充:

img {
    padding:100px;
    background: pink;
}
Run Code Online (Sandbox Code Playgroud)

结果是你的原始img每侧有100px的粉红色背景

在此输入图像描述

现在将width/height设置为0:

img {
   padding:100px;
   background: pink;
   width:0;height:0;
}
Run Code Online (Sandbox Code Playgroud)

你得到一个200px X 200px粉色区域:(所以现在你已经删除了原始图像)

在此输入图像描述

现在将粉红色背景更改为新背景

background: url(http://lorempixel.com/200/200) no-repeat;
Run Code Online (Sandbox Code Playgroud)

你完成了