Html 是否可以在 CSS 中设置 img 标签的 src 属性的等效项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2182716/
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
Is it possible to set the equivalent of a src attribute of an img tag in CSS?
提问by Rakesh Juyal
Is it possible to set the src
attribute value in CSS? At present, what iI am doing is:
是否可以src
在 CSS 中设置属性值?目前我在做的是:
<img src="pathTo/myImage.jpg"/>
and I want it to be something like this
我希望它是这样的
<img class="myClass" />
.myClass {
some-src-property: url("pathTo/myImage.jpg");
I want to do this withoutusing the background
or background-image:
properties in CSS.
我想在不使用CSS 中的background
orbackground-image:
属性的情况下做到这一点。
回答by Pacerier
Full working solution (Live Demo):
完整的工作解决方案 ( Live Demo):
<!doctype html>
<style>
.MyClass123{
content:url("http://imgur.com/SZ8Cm.jpg");
}
</style>
<img class="MyClass123"/>
Tested and working:
测试和工作:
- Chrome 14.0.835.163
- Safari 4.0.5
- Opera 10.6
- 铬 14.0.835.163
- Safari 4.0.5
- 歌剧 10.6
Tested and Notworking:
已测试但不工作:
- FireFox 40.0.2 (observing Developer Network Tools, you can see that the URL loads, but the image is not displayed)
- Internet Explorer 11.0.9600.17905 (URL never loads)
- FireFox 40.0.2(观察开发者网络工具,可以看到加载了URL,但是不显示图片)
- Internet Explorer 11.0.9600.17905(URL 从不加载)
回答by RobAu
There is a solution that I found out today (works in IE6+, FF, Opera, Chrome):
我今天发现了一个解决方案(适用于 IE6+、FF、Opera、Chrome):
<img src='willbehidden.png'
style="width:0px; height:0px; padding: 8px; background: url(newimage.png);">
How it works:
这个怎么运作:
- The image is shrunk until no longer visible by the width & height.
- Then, you need to 'reset' the image size with padding. This one gives a 16x16 image. Of course you can use padding-left / padding-top to make rectangular images.
- Finally, the new image is put there using background.
- If the new background image is too large or too small, I recommend using
background-size
for example:background-size:cover;
which fits your image into the allotted space.
- 图像缩小,直到宽度和高度不再可见。
- 然后,您需要使用填充“重置”图像大小。这个给出了一个 16x16 的图像。当然你可以使用 padding-left / padding-top 来制作矩形图像。
- 最后,使用背景将新图像放在那里。
- 如果新的背景图像太大或太小,我建议使用
background-size
例如:background-size:cover;
将您的图像放入分配的空间。
It also works for submit-input-images, they stay clickable.
它也适用于提交输入图像,它们保持可点击。
See live demo: http://www.audenaerde.org/csstricks.html#imagereplacecss
查看现场演示:http: //www.audenaerde.org/csstricks.html#imagereplacecss
Enjoy!
享受!
回答by CS?
A collection of possible methods to set images from CSS
从 CSS 设置图像的可能方法的集合
CSS2's :after
pseudo-element or the newersyntax ::after
from CSS3along with the content:
property:
CSS2的:after
伪元素或来自CSS3的更新语法以及属性: ::after
content:
First W3C Recommendation: Cascading Style Sheets, level 2
CSS2 Specification12 May 1998
Latest W3C Recommendation: Selectors Level 3
W3C Recommendation29 September 2011
第一个 W3C 建议:层叠样式表,级别 2 CSS2 规范1998 年 5 月 12 日
最新的 W3C 建议:选择器级别 3 W3C 建议2011 年 9 月 29 日
This method appendscontent just afteran element's document tree content.
此方法将内容附加在元素的文档树内容之后。
Note: some browsers experimentallyrender the content
property directly over someelement selectors disregarding even the latest W3C recommendation that defines:
注意:一些浏览器实验content
性地直接在一些元素选择器上渲染属性,甚至不顾定义的最新 W3C 建议:
Applies to:
:before
and:after
pseudo-elements
适用于:
:before
和:after
伪元素
CSS2 syntax (forward-compatible):
CSS2 语法(向前兼容):
.myClass:after {
content: url("somepicture.jpg");
}
CSS3 Selector:
CSS3 选择器:
.myClass::after {
content: url("somepicture.jpg");
}
Default rendering: Original Size(does not depend on explicit size declaration)
默认渲染:原始尺寸(不依赖于明确的尺寸声明)
This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.
本规范没有完全定义 :before 和 :after 与替换元素(例如 HTML 中的 IMG)的交互。这将在未来的规范中更详细地定义。
but even at the time of this writing, behaviour with a <IMG>
tag is still not defined and although it can be used in a hacked and non standards compliant way, usage with <img>
is not recommended!
但即使是在写这篇文章的时候,用行为<IMG>
标签尚未定义,虽然它可以被用在黑客攻击和不符合标准的方式,与使用<img>
不推荐!
Great candidate method, see conclusions...
伟大的候选方法,见结论...
CSS1CSS1的
background-image:
background-image:
财产: First W3C Recommendation: Cascading Style Sheets, level 117 Dec 1996
第一个 W3C 建议:层叠样式表,级别 1 1996 年 12 月 17 日
This property sets the background image of an element. When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.
此属性设置元素的背景图像。设置背景图像时,还应设置图像不可用时使用的背景颜色。当图像可用时,它会覆盖在背景颜色之上。
This property has been around from the beginning of CSS and nevertheless it deserve a glorious mention.
这个属性从 CSS 一开始就存在,但它值得一提。
Default rendering: Original Size(cannot be scaled, only positioned)
默认渲染:原始大小(无法缩放,只能定位)
However,
然而,
CSS3's background-size:
property improved on it by allowing multiple scaling options:
CSS3的background-size:
属性通过允许多个缩放选项对其进行了改进:
Latest W3C Status: Candidate RecommendationCSS Backgrounds and Borders Module Level 39 September 2014
最新的 W3C 状态:候选推荐CSS 背景和边框模块级别 3 2014 年 9 月 9 日
[length> | <percentage> | auto ]{1,2} | cover | contain
[length> | <percentage> | auto ]{1,2} | cover | contain
But even with this property, it depends on container size.
但即使有这个属性,它也取决于容器的大小。
Still a good candidate method, see conclusions...
还是不错的候选方法,看结论...
CSS2's list-style:
property along with display: list-item
:
CSS2的list-style:
属性以及display: list-item
:
First W3C Recommendation: Cascading Style Sheets, level 2 CSS2 Specification12 May 1998
第一个 W3C 建议:层叠样式表,级别 2 CSS2 规范1998 年 5 月 12 日
list-style-image:
property sets the image that will be used as the list item marker (bullet)
list-style-image:
属性设置将用作列表项标记(项目符号)的图像
The list properties describe basic visual formatting of lists: they allow style sheets to specify the marker type (image, glyph, or number)
列表属性描述了列表的基本视觉格式:它们允许样式表指定标记类型(图像、字形或数字)
display: list-item
— This value causes an element (e.g., <li>
in HTML) to generate a principal block box and a marker box.
display: list-item
— 该值使元素(例如,<li>
在 HTML 中)生成主块框和标记框。
.myClass {
display: list-item;
list-style-position: inside;
list-style-image: url("someimage.jpg");
}
Shorthand CSS: (<list-style-type> <list-style-position> <list-style-image>
)
CSS 简写: ( <list-style-type> <list-style-position> <list-style-image>
)
.myClass {
display: list-item;
list-style: square inside url("someimage.jpg");
}
Default rendering: Original Size(does not depend on explicit size declaration)
默认渲染:原始尺寸(不依赖于明确的尺寸声明)
Restrictions:
限制:
Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.
They do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker or adjust its position
继承会将“列表样式”值从 OL 和 UL 元素转移到 LI 元素。这是指定列表样式信息的推荐方式。
它们不允许作者为列表标记指定不同的样式(颜色、字体、对齐方式等)或调整其位置
This method is also not suitable for the <img>
tag as the conversion cannot be made between element types, and here's the limited, non compliant hackthat doesn't work on Chrome.
这种方法也不适合<img>
标签,因为不能在元素类型之间进行转换,这里是有限的、不兼容的 hack,它在 Chrome 上不起作用。
Good candidate method, see conclusions...
不错的候选方法,看结论...
CSS3's border-image:
property recommendation:
CSS3的border-image:
属性推荐:
Latest W3C Status: Candidate RecommendationCSS Backgrounds and Borders Module Level 39 September 2014
最新的 W3C 状态:候选推荐CSS 背景和边框模块级别 3 2014 年 9 月 9 日
A background-typemethod that relies on specifying sizes in a rather peculiar manner (not defined for this use case)and fallback border properties so far(eg. border: solid
):
甲背景型依赖于在一个比较奇特方式指定尺寸的方法(用于该用途的情况下,没有定义)和回退边框属性迄今(例如border: solid
):
Note that, even though they never cause a scrolling mechanism, outset images may still be clipped by an ancestor or by the viewport.
请注意,即使它们从不引起滚动机制,初始图像仍可能被祖先或视口剪裁。
This example illustrates the image being composedonly as a bottom-right corner decoration:
这个例子说明了图像感构成仅作为右下角装饰:
.myClass {
border: solid;
border-width: 0 480px 320px 0;
border-image: url("http://i.imgur.com/uKnMvyp.jpg") 0 100% 100% 0;
}
Applies to: All elements, except internal table elements when
border-collapse: collapse
适用于:所有元素,当内部表格元素除外
border-collapse: collapse
Still it can't changean <img>
's tag src
(but here's a hack), instead we can decorate it:
不过它不能改变一个<img>
的标签src
(但这里的一个黑客),相反,我们可以装点它:
.myClass {
border: solid;
border-width: 0 96px 96px 0;
border-image: url("http://upload.wikimedia.org/wikipedia/commons/9/95/Christmas_bell_icon_1.png")
0 100% 100% 0;
}
<img width="300" height="120"
src="http://fc03.deviantart.net/fs71/f/2012/253/b/0/merry_christmas_card_by_designworldwide-d5e9746.jpg"
class="myClass"
Good candidate method to be considered after standards propagate.
标准传播后要考虑的良好候选方法。
CSS3's element()
notation working draftis worth a mention also:
CSS3的element()
符号工作草案也值得一提:
Note: The
element()
function only reproduces the appearanceof the referenced element, not the actual content and its structure.
注意:该
element()
功能仅再现引用元素的外观,而非实际内容及其结构。
<div id="img1"></div>
<img id="pic1" src="http://i.imgur.com/uKnMvyp.jpg" class="hide" alt="wolf">
<img id="pic2" src="http://i.imgur.com/TOUfCfL.jpg" class="hide" alt="cat">
We'll use the rendered contentsof one of the two hidden imagesto change the image backgroundin #img1
based on the ID Selectorvia CSS:
我们将使用呈现内容两者之一的隐藏图像来改变图像背景中的#img1
基础上,ID选择通过CSS:
#img1 {
width: 480px;
height: 320px;
background: -moz-element(#pic1) no-repeat;
background-size: 100% 100%;
}
.hide {display: none}
Notes: It's experimentaland only works with the -moz
prefix in Firefox and only over background
or background-image
properties, also needs sizes specified.
注意:它是实验性的,仅适用-moz
于 Firefox 中的前缀,并且仅适用于background
或background-image
属性,还需要指定大小。
Conclusions
结论
- Any semantic content or structural information goes in HTML.
- Styling and presentational information goes in CSS.
- For SEO purposes, don't hidemeaningful images in CSS.
- Background graphics are usually disabled when printing.
- Custom tagscould be used and styled from CSS, but primitiveversions of Internet Explorer do not understand](IE not styling HTML5 tags (with shiv)) without Javascript or CSS guidance.
- SPA's (Single Page Applications), by design, usually incorporate images in the background
- 任何语义内容或结构信息都在 HTML 中。
- 样式和表现信息在 CSS 中。
- 出于 SEO 的目的,不要在 CSS 中隐藏有意义的图像。
- 打印时通常禁用背景图形。
- 自定义标签可以从 CSS 中使用和样式化,但原始版本的 Internet Explorer 不理解](IE 不样式化 HTML5 标签(使用 shiv))没有 Javascript 或 CSS指导。
- SPA(单页应用程序)在设计上通常在背景中包含图像
Having said that, let's explore HTML tags fit for image display:
话虽如此,让我们探索适合图像显示的 HTML 标签:
The <li>
element [HTML4.01+]
所述<li>
元素[HTML4.01 +]
Perfect usecase of the list-style-image
with display: list-item
method.
list-style-image
withdisplay: list-item
方法的完美用例。
The <li>
element, can be empty, allows flow contentand it's even permitted to omit the </li>
end tag.
该<li>
元素可以是空的,可以流动的内容,它甚至允许真实省略</li>
结束标记。
.bulletPics > li {display: list-item}
#img1 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/4/4d/Nuvola_erotic.png")}
#img2 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/7/74/Globe_icon_2014-06-26_22-09.png")}
#img3 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/c/c4/Kiwi_fruit.jpg")}
<ul class="bulletPics">
<li id="img1">movie</li>
<li id="img2">earth</li>
<li id="img3">kiwi</li>
</ul>
Limitations: hard to style (width:
or float:
might help)
限制:难以设计(width:
或float:
可能有帮助)
The <figure>
element [HTML5+]
所述<figure>
元素[HTML5 +]
The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.
图元素表示一些流内容,可选地带有标题,它是自包含的(如完整的句子),通常作为文档主要流中的单个单元引用。
The element is valid with no content, but is recommended to contain a <figcaption>
.
该元素在没有内容时有效,但建议包含<figcaption>
.
The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc.
因此,该元素可用于注释插图、图表、照片、代码清单等。
Default rendering: the element is right aligned, with both left and right padding!
默认渲染:元素右对齐,左右填充!
The <object>
element [HTML4+]
所述<object>
元素[HTML4 +]
To include images, authors may use the OBJECT element or the IMG element.
为了包含图像,作者可以使用 OBJECT 元素或 IMG 元素。
The data
attribute is required and can have a valid MIME typeas a value!
该data
属性是必需的,并且可以具有有效的MIME 类型作为值!
<object data="data:x-image/x,"></object>
Note: a trick to make use of the <object>
tag from CSS would be to set a customvalid MimeType x-image/x
followed by no data (value has no data after the required comma ,
)
注意:使用<object>
CSS中的标签的一个技巧是设置一个 自定义的有效 MimeType,x-image/x
后跟没有数据(值在所需的逗号之后没有数据,
)
Default rendering: 300 x 150px, but size can be specified either in HTML or CSS.
默认渲染:300 x 150px,但可以在 HTML 或 CSS 中指定大小。
The <SVG>
tag
该<SVG>
标签
Needs a SVG capable browserand has a <image>
element for raster images
需要一个支持 SVG 的浏览器,并且有一个<image>
用于光栅图像的 元素
The <canvas>
element [HTML5+].
所述<canvas>
元素[HTML5 +]。
The
width
attribute defaults to 300, and theheight
attribute defaults to 150.
的
width
属性默认为300,并且height
属性默认为150。
The <input>
element with type="image"
在<input>
与元素type="image"
Limitations:
限制:
... the element is expected to appear button-like to indicate that the element is a button.
...该元素应该看起来像按钮,以表明该元素是一个按钮。
which Chrome follows and renders a 4x4px empty square when no text
当没有文本时,Chrome 跟随并呈现一个 4x4px 的空方块
Partial solution, set value=" "
:
部分解决方案,设置value=" "
:
<input type="image" id="img1" value=" ">
Also watch out for the upcoming <picture>
element in HTML5.1, currently a working draft.
还要注意HTML5.1 中即将出现的<picture>
元素,目前是一个工作草案。
回答by Emmanuel Touzery
i used the empty div solution, with this CSS:
我使用了空的 div 解决方案,带有这个 CSS:
#throbber {
background-image: url(/Content/pictures/ajax-loader.gif);
background-repeat: no-repeat;
width: 48px;
height: 48px;
min-width: 48px;
min-height: 48px;
}
HTML:
HTML:
<div id="throbber"></div>
回答by EricG
I found a better way than the proposed solutions, but it does use the background-image indeed. Compliant method (cannot confirm for IE6)Credits: http://www.kryogenix.org/code/browser/lir/
我找到了比建议的解决方案更好的方法,但它确实使用了背景图像。 兼容方法(无法确认 IE6)积分:http: //www.kryogenix.org/code/browser/lir/
<img src="pathTo/myImage.jpg"/>
The CSS:
CSS:
img[src*="pathTo/myImage.jpg"] {
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
width: 20px;
display:inline-block;
padding: 20px 0 0 0;
height: 0px !important;
/* for IE 5.5's bad box model */
height /**/:20px;
}
The old image is not seen and the new is seen as expected.
旧图像未显示,新图像按预期显示。
The following neat solution only works for webkit
以下简洁的解决方案仅适用于 webkit
img[src*="pathTo/myImage.jpg"] {
/* note :) */
content:'';
display:inline-block;
width: 20px;
height: 20px;
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
}
回答by Frank
They are right. IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS).
他们是对的。IMG 是一个内容元素,而 CSS 是关于设计的。但是,当您出于设计目的使用某些内容元素或属性时呢?我的网页上有 IMG,如果我更改样式(CSS),这些 IMG 必须更改。
Well this is a solution for defining IMG presentation (no really the image) in CSS style.
嗯,这是在 CSS 样式中定义 IMG 演示文稿(实际上不是图像)的解决方案。
- create a 1x1 transparent gif or png.
- Assign propery "src" of IMG to that image.
- Define final presentation with "background-image" in the CSS style.
- 创建一个 1x1 透明的 gif 或 png。
- 将 IMG 的属性“src”分配给该图像。
- 在 CSS 样式中使用“background-image”定义最终演示文稿。
It works like a charm :)
它就像一个魅力:)
回答by OviC
Here is a very good solution -> http://css-tricks.com/replace-the-image-in-an-img-with-css/
Pro(s) and Con(s):
(+) works with vector image that have relative width/height (a thing that RobAu's answerdoes not handle)
(+) is cross browser (works also for IE8+)
(+) it only uses CSS. So no need to modify the img src (or if you do not have access/do not want to change the already existing img src attribute).
(-) sorry, it does usethe background css attribute :)
这是一个非常好的解决方案 -> http://css-tricks.com/replace-the-image-in-an-img-with-css/
Pro(s) and Con(s):
(+) 使用矢量具有相对宽度/高度的图像(RobAu的答案不处理)
(+)是跨浏览器(也适用于 IE8+)
(+)它只使用 CSS。因此无需修改 img src(或者如果您没有访问权限/不想更改已经存在的 img src 属性)。
(-) 抱歉,它确实使用了背景 css 属性 :)
回答by Kostas Andrianopoulos
You can define 2 images in your HTML code and use display: none;
to decide which one will be visible.
您可以在 HTML 代码中定义 2 个图像,并用于display: none;
决定哪一个可见。
回答by cletus
No you can't set the image src attribute via CSS. The closest you can get is, as you say, background
or background-image
. I wouldn't recommend doing that anyway as it would be somewhat illogical.
不,您不能通过 CSS 设置图像 src 属性。你能得到的最接近的是,正如你所说的,background
或者background-image
。无论如何,我不建议这样做,因为这有点不合逻辑。
However, there is a CSS3 solution available to you, if the browsers you're targeting are able to use it. Use content:url
as described in Pacerier's answer. You can find other, cross-browser solutions in the other answers below.
但是,如果您的目标浏览器能够使用 CSS3 解决方案,您可以使用它。content:url
按照 Pacerier 的回答中所述使用。您可以在下面的其他答案中找到其他跨浏览器解决方案。
回答by Bronx
Put several images in a "controlling" container, and change the container's class instead. In CSS, add rules to manage images' visibility depending on the container's class. This will produce the same effect as changing img src
property of a a single image.
将多个图像放入“控制”容器中,并改为更改容器的类。在 CSS 中,添加规则以根据容器的类来管理图像的可见性。这将产生与更改img src
单个图像的属性相同的效果。
HTML:
HTML:
<span id="light" class="red">
<img class="red" src="red.png" />
<img class="yellow" src="yellow.png" />
<img class="green" src="green.png" />
</span>
CSS:
CSS:
#light { ... }
#light * { display: none; } // all images are hidden
#light.red .red { display: inline; } // show red image when #light is red
#light.yellow .yellow { display: inline; } // .. or yellow
#light.green .green { display: inline; } // .. or green
Note that it will preload all images, like with CSS backround-image
s, but unlike changing img src
via JS.
请注意,它将预加载所有图像,就像使用 CSS 一样backround-image
,但与img src
通过 JS更改不同。