:before 对 img 元素不起作用吗? [英] Does :before not work on img elements?

查看:47
本文介绍了:before 对 img 元素不起作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 :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 篇博文想要修改,我可以做到一次性修改样式表,但如果我必须返回并在 aimg 之间添加一个额外的 span 元素> 元素,这将是更多的工作.

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-img 标签属性

但是,您可以使用 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.

这篇关于:before 对 img 元素不起作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆