【问题记录】为什么给元素添加伪元素会无效

1,920 阅读2分钟

这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战

前言

哈喽,大家好哇,欢迎来到大冰块的博客,今天我们来谈谈给元素添加伪元素那点事儿。

总所周知,扩大点击热区最方便的方法之一就是给当前点击元素添加伪元素,伪元素的点击同样会被应用在当前元素上,而今天我在给img标签添加伪元素的时候,死活找不到添加的伪元素在哪。

问题开始

代码如下:

    <style>
        .logo{
            width: 36px;
            height: 36px;
            position: relative;
        }
        .logo::before{
            content: "";
            position: absolute;
            top: -10px;
            right: -10px;
            bottom: -10px;
            left: -10px;
            background-color: rgba(138, 248, 165, 0.5);
        }
    </style>


    <img src="./img/logo.jpg" alt="" class="logo">

实现效果如下:

image.png

我的伪元素呢?为什么伪元素没有生效???

问题分析

这一度让我怀疑自己是不是单词哪里拼错了。 在我再三检查之后,终于确认不是拼错了单词。 苦苦思考终于想到:

伪元素并不是一个dom节点,它的content是插入在当前元素内容的前后,而不是当前元素的前后。对于不会存在内容和后代元素的元素来说,伪元素自然不会生效。

想到这里我立马翻出了w3c对应的文档

image.png

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.

文档写的明明白白,before和:after伪元素用来指定元素文档树内容前后的内容的,并没有添加新的节点。

再看看下面这个说明:

image.png

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这样的自闭合的标签(可替换元素),由于并没有内容,也没有后代元素,所以现在暂未定义(浏览器会有差异),以后会定义呗。

怎么解决呢?

问题解决

既然是因为当前元素没有给当前元素添加content属性是个不错的选择,不过既然浏览器会有差异,还是要换个保险的方式来实现:

包裹一层标签,给父级元素添加伪元素即可。

代码如下:

    <style>
        .logo{
            width: 36px;
            height: 36px;
            position: relative;
        }
        .logo::before{
            content: "";
            position: absolute;
            top: -10px;
            right: -10px;
            bottom: -10px;
            left: -10px;
            background-color: rgba(138, 248, 165, 0.5);
        }
    </style>

    <div class="logo">
        <img src="./img/logo.jpg" alt="" class="logo">
    </div>

实现效果如下:

image.png

完美!

后记

你好哇,我是南极大冰块,一个技术与颜值成正比的前端工程师,崇尚一针见血的搞定前端问题,希望我的博客有帮助到了你。关注我,前端路途一起走。嘿哈~😛