You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

伪元素::after未显示问题求助(附代码示例)

解决伪元素::after不显示的问题

你的代码里伪元素不显示的核心原因是:<img>属于替换元素,这类元素的内容由外部资源(比如你引入的svg图片)决定,浏览器默认不会为替换元素生成::before或::after伪元素。

另外还有一个细节:即使是非替换元素,伪元素默认是inline状态,设置宽高也不会生效,所以还需要调整伪元素的显示模式或定位方式。

下面给你两种可行的修改方案:

方案一:给图片套容器,伪元素加在容器上

修改HTML结构,给<img>包裹一个容器,把伪元素绑定到这个容器上:

<div class="nav-container">
    <div class="nav-icon-wrapper">
        <img class="nav-icon" src="img/nav-1.svg" alt="">
    </div>
    <div class="nav-text">Campus AI</div>
</div>

对应的CSS调整:

.nav-icon {
    height: 24px;
    width: 24px;
    margin-bottom: 8px;
}

.nav-text {
    font-weight: 400;
}

.nav-container:hover > .nav-text {
    font-weight: 700;
}

/* 给容器添加伪元素 */
.nav-container:hover > .nav-icon-wrapper::after {
    content: "";
    width: 40px;
    height: 30px;
    background-color: #fff;
    border-radius: 12px;
    /* 用绝对定位控制伪元素位置,需要给父容器设置相对定位 */
    position: absolute;
    top: 0;
    left: 0;
}

.nav-icon-wrapper {
    position: relative; /* 作为伪元素的定位上下文 */
    display: inline-block; /* 适配图片的尺寸 */
}

方案二:用背景图替代img标签

把<img>换成<div>,用background-image引入图标,这样这个div就是非替换元素,可以正常生成伪元素:

<div class="nav-container">
    <div class="nav-icon"></div>
    <div class="nav-text">Campus AI</div>
</div>

对应的CSS调整:

.nav-icon {
    height: 24px;
    width: 24px;
    margin-bottom: 8px;
    background-image: url('img/nav-1.svg');
    background-size: cover; /* 让背景图适配容器大小 */
    position: relative; /* 为伪元素提供定位上下文 */
}

.nav-text {
    font-weight: 400;
}

.nav-container:hover > .nav-text {
    font-weight: 700;
}

.nav-container:hover > .nav-icon::after {
    content: "";
    width: 40px;
    height: 30px;
    background-color: #fff;
    border-radius: 12px;
    position: absolute;
    top: 0;
    left: 0;
}

内容的提问来源于stack exchange,提问作者Evgeny Nonin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 18:57:48