如何让动画显示在登录框后方?CSS层级问题修正方法
问题解决办法
要让section的背景动画显示在登录框后方,只需对section及其伪元素做以下两处关键修改:
1. 调整section的基础样式(可选但推荐)
给section添加overflow: hidden;,避免动画超出视口范围:
section { position: absolute; display: flex; width: 100vw; height: 100vh; justify-content: center; align-items: center; gap: 2px; flex-wrap: wrap; overflow: hidden; /* 新增:防止动画溢出 */ }
2. 重写section::before的定位与层级
原伪元素使用position: relative会导致堆叠层级高于登录框,需要修改为绝对定位并降低层级:
section::before { content: ''; position: absolute; /* 从relative改为absolute */ top: 0; /* 新增:让伪元素铺满section顶部 */ left: 0; /* 新增:让伪元素铺满section左侧 */ width: 100%; height: 100%; background: linear-gradient(rgb(0, 0, 0), rgba(5, 189, 230, 0.922), #000); animation: animate 5s linear infinite; z-index: 0; /* 新增:设置层级低于登录框的1000 */ }
原理说明
- 伪元素改为
position: absolute后,会相对于已设置position: absolute的父元素section定位,通过top:0;left:0;width:100%;height:100%铺满整个section作为背景。 z-index:0确保伪元素堆叠层级低于登录框的z-index:1000,同时也低于section内span的z-index:2,动画就会被所有前景元素覆盖,仅作为背景显示。
内容的提问来源于stack exchange,提问作者Ceylon_king
相关产品推荐
相关产品推荐

