Html 将 ::after 与图像标签一起使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26371129/
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-29 02:52:06  来源:igfitidea点击:

Using ::after with an image tag?

htmlcss

提问by Jay Blanchard

Is it possible to append text to images using the ::afterpseudo-selector?

是否可以使用::after伪选择器将文本附加到图像?

img[src="images/interface-zoom-buttons.png"]::after {
    content: "these are the zoom buttons";
}

The desire is to use the selector to provide a caption (other styling will be applied to the content of the selector) for images that get used over and over again in multiple HTML documents.

希望使用选择器为在多个 HTML 文档中反复使用的图像提供标题(其他样式将应用于选择器的内容)。

In the above example the image appears correctly and you can see that the appropriate CSS has been applied, but the content (supplied by the selector) is not seen in the output.

在上面的示例中,图像正确显示,您可以看到已应用适当的 CSS,但在输出中看不到内容(由选择器提供)。

回答by Arbel

An img tag can not have child elements. Because imgis a void elementand its content model never allows it to have contents under any circumstances.

img 标签不能有子元素。因为img是一个空元素,它的内容模型在任何情况下都不允许它有内容。

::aftercreates a pseudo element as the last child of its parent.

::after创建一个伪元素作为其父元素的最后一个子元素。

So img::afterwill not work ultimately because the browser will not allow it based on definition.

所以img::after最终不会工作,因为浏览器不会允许它基于定义。

What you can do is to contain the imgin a container and have ::afteron the container.

您可以做的是将 包含img在容器中并::after放在容器上。

Demohttp://jsfiddle.net/x2za91jw/

演示http://jsfiddle.net/x2za91jw/

HTML

HTML

<div class="container">
    <img src="http://www.gazette-ariegeoise.fr/IMG/jpg/test.jpg" />
</div>

CSS

CSS

.container {
    position: relative;
}
.container::after {
    position: absolute;
    top: 0;
    left: 0;
    border: 1px solid #000;
    content:"these are the zoom buttons";
}