对img标签使用after和before伪元素失效的原因

img标签的before,after伪类

content是插入在元素内容的前后,而不是元素的前后

比如":before" 伪元素可以在元素的内容前面插入新内容。

下面的例子在每个 <h1> 元素前面插入一幅图片:

h1:before
  {
  content:url(logo.gif);
  }

在CSS中总有一些你不用不知道,用到才知道的“坑”。比如今天要谈的,把 before, after 伪类用在 <img> 标签上。
嗯,实际上你用你会发现,在大多数浏览器这是无效的,dom中并不会出现你想要的结果。
为什么会这样呢?
让我们回归到 W3C 标准中寻觅一下,在标准中,before, after 伪类的定义如:

As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content.
来自 https://www.w3.org/TR/CSS21/generate.html#before-after-content

我们应该注意到所谓 document tree content,对于 img 这种自闭和标签,似乎不存在 content (内容或后代元素)在标签中,所以选择器没有生效。但这样的解释还不够清晰,实际上标准中还有一行注释:

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.

嗯,这回清楚了,对于可替换元素(如 img、input、select 等),标准并没有清晰定义,这也导致了浏览器实现的差异性。
有解决办法么?搜了一下是有的(http://stackoverflow.com/questions/5843035/does-before-not-work-on-img-elements):

使用jQuery

使用 jQuery 的 before,after 方法:
javascript
$('.target').after('<img src="..." />');

实际上,jQuery 只是在目标元素前后插入 dom 而已。

伪造 content

给 img 这类标签添加 content 属性,输入一些无意义的文本,让浏览器认为标签含有 content。
如在 CSS 中添加:
css
 

img {
/* hide the default image */
height:0;
width:0;
/* hide fake content */
font-size:0;
color:transparent;
/* enable absolute position for pseudo elements */
position:relative;
/* and this is just fake content */
content:"I'm just fake content";
}

但这种方法存在浏览器兼容问题。

所以最后还是建议不要做这种尝试了,给父标签添加伪类吧。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值