:before 不适用于 img 元素吗?

2022-01-30 00:00:00 html css

我正在尝试使用 :before 选择器将图像放在另一个图像上,但我发现将图像放在 img 之前根本不起作用 元素,只有一些其他元素.具体来说,我的风格是:

I'm trying to use the :before selector to place an image over another image, but I'm finding that it simply doesn't work to place an image before an img element, only some other element. Specifically, my styles are:

.container
{
   position: relative;
   display: block;
}

.overlay:before
{
    content: url(images/[someimage].png);
    position: absolute;
    left:-20px;
    top: -20px;
}

我发现这很好用:

<a href="[url]" class="container">
  <span class="overlay"/>
  <img width="200" src="[url]"/>
</a>

但事实并非如此:

<a href="[url]" class="container">
  <img width="200" src="[url]" class="overlay"/>
</a>

我可以使用 divp 元素代替 span,并且浏览器可以正确地将我的图像覆盖在 img 元素,但是如果我将覆盖类应用到 img 本身,它就不起作用了.

I can use a div or p element instead of that span, and the browser correctly overlays my image over the image in the img element, but if I apply the overlay class to the img itself, it doesn't work.

我想让这个工作,因为额外的 span 冒犯了我,但更重要的是,我有大约 100 篇我想修改的博客文章,我可以这样做如果我可以直接修改样式表,但如果我必须返回并在 aimgspan 元素> 元素,这将是更多的工作.

I'd like to get this working because that extra span offends me, but more importantly, I've got about 100 blog posts that I'd like to modify, and I can do this in one go if I could just modify the stylesheet, but if I have to go back and add an extra span element in between the a and img elements, this will be a lot more work.

推荐答案

很遗憾,大多数浏览器不支持在 img 标签上使用 :after:before.

Unfortunately, most browsers do not support using :after or :before on img tags.

http://lildude.co.uk/after-css-属性换图像标签

但是,您可以使用 JavaScript/jQuery 完成所需的工作.看看这个小提琴:

However, it IS possible for you to accomplish what you need with JavaScript/jQuery. Check out this fiddle:

http://jsfiddle.net/xixonia/ahnGT/

$(function() {

    $('.target').after('<img src="..." />');

});

编辑:

关于不支持此功能的原因,请查看 coreyward 的回答.

For the reason why this isn't supported, check out coreyward's answer.

相关文章