css - 如何使用 CSS 显示 img alt 文本?

标签 css

<分区>

我已经试过了,效果很好

<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

关于css - 如何使用 CSS 显示 img alt 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188691/

相关文章:

html - Foundation 5.2 - 下拉子菜单方向

javascript - 如何将 2 个图标/图像合二为一?

Javascript 工具提示不起作用,不知道为什么

html - CSS 下拉菜单不会在胡佛上打开

javascript - 文本中的 Css 链接

javascript - 将类添加到备用元素并为每个容器重新启动

html - 为什么 GitHub Pages 不将 CSS 应用到其他页面?

html - 让非固定宽度的 div 完美适合父级而不会溢出?

javascript - 从另一个 Accordion 链接到 Accordion 内的内容

python - 垂直滚动条django-tables2