我已经试过了,效果很好
<p alt="world">hello</p>
使用 CSS
p::after {
content: attr(alt);
}
但是我试了一下还是不行
<img src="http://placehold.it/300x300" alt="my image caption">
使用 CSS
img::after {
content: attr(alt);
}
是否可以使用 CSS 为 img
输出替代文本?
请指明浏览器与您提供的任何解决方案的兼容性。
Here's a jsfiddle
这是设计使然。
img
标签是自闭合 ( <tag />
) 标签,因此它们不包含“内容”。由于它们不包含任何内容,因此没有 content
可以附加(即 ::after
)或前置(即 ::before
)。
其他自闭合 HTML 元素也是如此:
<area>
, <base>
, <br>
, <col>
, <command>
, <embed>
, <hr>
, <keygen>
,
<link>
, <meta>
, <param>
, <source>
, <track>
and <wbr>
这是 (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]
来源: http://www.w3.org/TR/CSS2/generate.html#before-after-content