【问题标题】:replace content of img via css通过css替换img的内容
【发布时间】:2017-09-06 15:55:38
【问题描述】:

我有这个图片标签:

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

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

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

它在 chrome 上运行良好,但在 firefox 上运行良好,即,知道为什么吗?

【问题讨论】:

标签: html image css


【解决方案1】:

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

2) 添加 100px 的内边距。

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

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

这是如何工作的?

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

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

结果是你的原始图片,每边都有 100px 的粉红色背景

现在将宽度/高度设置为 0:

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

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

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

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

你就完成了。

【讨论】:

  • 哇,非常好的技巧。您可以只将width(但不能将height)设置为0,并将填充设置为0 50%。然后它将适用于任何图像大小。
【解决方案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 */
  }

【讨论】:

  • 我认为是上一个答案的副本
猜你喜欢
  • 2013-08-04
  • 2011-10-20
  • 2016-11-04
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2010-10-03
相关资源
最近更新 更多