如何使用 CSS 显示 img alt 文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23188691/
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
How to display img alt text using CSS?
提问by Thank you
I've tried this and it works fine
我试过这个,它工作正常
<p alt="world">hello</p>
With CSS
使用 CSS
p::after {
content: attr(alt);
}
But it doesn't work when I try
但是当我尝试时它不起作用
<img src="http://placehold.it/300x300" alt="my image caption">
With CSS
使用 CSS
img::after {
content: attr(alt);
}
Is it possible to output alt text for an img
using CSS?
是否可以为img
使用 CSS输出替代文本?
Please indicate browser compatibility with any solution you provide.
请说明浏览器与您提供的任何解决方案的兼容性。
回答by adaam
This is by design.
这是设计使然。
img
tags are self-closing (<tag />
) tag, and therefore they contain no "content". Since they do not contain any content, no content
can be appended (i.e. ::after
) or prepended (i.e. ::before
).
img
标签是自闭合 ( <tag />
) 标签,因此它们不包含“内容”。由于它们不包含任何内容,因此content
不能附加(即::after
)或前置(即::before
)。
This is also the case for other self-closing HTML elements:
其他自闭合 HTML 元素也是如此:
<area>
,<base>
,<br>
,<col>
,<command>
,<embed>
,<hr>
,<keygen>
,<link>
,<meta>
,<param>
,<source>
,<track>
and<wbr>
<area>
,<base>
,<br>
,<col>
,<command>
,<embed>
,<hr>
,<keygen>
,<link>
,<meta>
,<param>
,<source>
,<track>
和<wbr>
Here's what the (CSS2) Spec says:
这是(CSS2)规范所说的:
Note. 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. [2014: hasn't happened yet]
笔记。本规范没有完全定义 :before 和 :after 与替换元素(例如 HTML 中的 IMG)的交互。这将在未来的规范中更详细地定义。[2014:尚未发生]
Source:http://www.w3.org/TR/CSS2/generate.html#before-after-content
来源:http : //www.w3.org/TR/CSS2/generate.html#before-after-content