Does :before not work on img elements?(: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>
我可以使用 div
或 p
元素代替 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 篇我想修改的博客文章,我可以这样做如果我可以直接修改样式表,但如果我必须返回并在 a
和 img
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-属性换图像标签
但是,您可以使用 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 元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为::before 不适用于 img 元素吗?


基础教程推荐
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01