CSS img 元素的 content 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11173991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:16:57  来源:igfitidea点击:

content attribute of img elements

google-chromecssimageweb-standards

提问by Maximilian Hils

While inspecting the Chrome Dev tools, I noticed the following CSS fragment:

在检查 Chrome Dev 工具时,我注意到以下 CSS 片段:

img {
    content: url(image-src.png);
}

which works perfectly in Chrome (see Screenshot below).

它在 Chrome 中完美运行(请参阅下面的屏幕截图)。

Chrome Dev Tools

Chrome 开发工具

This allows me to define the src attribute of an <img> tag via CSS. Doesn't work in Firefox. Until now I thought that is not possible to directly modify the src attribute via css and I have not found anyone talking about this. So, is this just a proprietary addition in Chrome or is Chrome implementing a W3C draft or something comparable I am not aware of?

这允许我通过 CSS 定义 <img> 标签的 src 属性。在 Firefox 中不起作用。直到现在我认为通过 css 直接修改 src 属性是不可能的,我还没有发现任何人在谈论这个。那么,这只是 Chrome 中的专有附加功能,还是 Chrome 实现了 W3C 草案或我不知道的类似内容?

回答by Jukka K. Korpela

The contentproperty as defined in CSS 2.1applies to :beforeand :afterpseudo-elements only. By CSS rules, you can specify any property for any element, but specifications have limitations on what properties “apply to” (i.e., have effect on) various elements.

contentCSS 2.1 中定义的属性仅适用于:before:after伪元素。通过 CSS 规则,您可以为任何元素指定任何属性,但规范对哪些属性“应用于”(即,对)各种元素有限制。

The CSS3 Generated and Replaced Content Module, a Working Draft, describes the contentpropertyas applying to all elements. It has an example of replacing the content of an h1element by an image, and surely the same could be done to an imgelement.

CSS3产生并代替内容模块,一个工作草案,描述了content属性为适用于所有元素。它有一个用h1图像替换元素内容的例子,当然也可以对img元素做同样的事情。

But it's just a Working Draft. The usual resources on CSS implementation status, QuirksMode.org CSS infoand Caniuse.com, do not indicate the situation; they only describe the support to contentfor :beforeand :after(which is rather universal except IE 7 and earlier.

但这只是一个工作草案。CSS 实现状态的常用资源QuirksMode.org CSS infoCaniuse.com没有说明情况;他们只描述了content:beforeand的支持:after(除了 IE 7 及更早版本,这是相当普遍的。

回答by Baghera

Now you can do that:http://chabada.esy.es/tests/0004.html

现在你可以这样做:http : //chabada.esy.es/tests/0004.html

<style>
  .redcross {
    background: transparent url('redcross.png') no-repeat;
    display: block;
    width:  24px;
    height: 24px;
    }
</style>

<img class="redcross">