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

如何将已实现的CSS transition按钮动画应用到网站导航li标签上

实现方案

你需要修改现有SCSS代码,用伪元素实现从左到右滑入的背景动画,修改后的完整SCSS如下:

nav,
.left-side {
    @include flex(space-between, center, column);
    min-height: 90vh;
    background: $color-grey-dark-1;
    padding: 5rem 0 3rem 0;
    width: 18%;
    color: $color-grey-light-1;
}

.navigations {
    width: 100%;

    li {
        list-style: none;

        a {
            text-decoration: none;
            color: $color-grey-light-1;
            display: block;
            padding: 2rem 0;
            margin: 0.5rem 0;
            padding-left: 30%;
            font-size: 2.5rem;
            /* 新增:相对定位,给伪元素做定位基准 */
            position: relative;
            /* 新增:避免伪元素超出a标签范围 */
            overflow: hidden;
            /* 新增:文字层级高于背景伪元素 */
            z-index: 1;
        }
        /* 新增:滑入背景伪元素 */
        a::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 0;
            height: 100%;
            background: $color-primary-light;
            /* 动画过渡效果,可根据需求调整时长 */
            transition: width 0.3s ease;
            /* 伪元素层级低于文字 */
            z-index: -1;
        }
    }
}
/* 替换原有hover样式 */
.navigations li a:hover::before {
    width: 100%;
}

核心修改说明

  • 给导航的a标签增加相对定位、溢出隐藏属性,作为伪元素的定位容器
  • 新增::before伪元素作为滑入背景,默认宽度为0,设置transition过渡动画
  • 把原来的a标签hover背景样式替换为hover时伪元素宽度变为100%,实现从左到右滑入的填充效果
  • 通过z-index控制层级,保证文字始终显示在背景上方,不会被背景遮挡

内容的提问来源于stack exchange,提问作者Adam Tose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:15:06