css动态背景制作
CSS动态背景制作方法
渐变动态背景
使用CSS的linear-gradient和animation属性创建颜色渐变变化效果:
body {
background: linear-gradient(45deg, #ff9a9e, #fad0c4, #fbc2eb);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
}
@keyframes gradientBG {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
粒子动画背景 通过伪元素创建移动粒子效果:
body {
position: relative;
overflow: hidden;
height: 100vh;
}
body::before {
content: "";
position: absolute;
width: 200vmax;
height: 200vmax;
background:
radial-gradient(circle, rgba(255,255,255,0.8) 2px, transparent 2px);
background-size: 20px 20px;
animation: move 100s linear infinite;
}
@keyframes move {
100% { transform: translate(50%, 50%); }
}
视差滚动背景 结合多层背景实现视差效果:
.parallax {
perspective: 1px;
height: 100vh;
overflow-x: hidden;
overflow-y: auto;
}
.parallax__layer {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.parallax__layer--base {
transform: translateZ(0);
}
.parallax__layer--back {
transform: translateZ(-1px) scale(2);
}
SVG动画背景 使用SVG结合CSS动画:
<div class="svg-bg">
<svg viewBox="0 0 100 100" preserveAspectRatio="none">
<path d="M0,0 L100,0 L100,100 L0,100 Z" fill="#4b6cb7">
<animate attributeName="d"
dur="10s"
repeatCount="indefinite"
values="M0,0 L100,0 L100,100 L0,100 Z;
M0,0 L100,20 L100,80 L0,100 Z;
M0,0 L100,0 L100,100 L0,100 Z"/>
</path>
</svg>
</div>
.svg-bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
CSS变量控制动态背景 通过JavaScript动态改变CSS变量值:
:root {
--bg-color-1: #ff9a9e;
--bg-color-2: #fad0c4;
--bg-angle: 45deg;
}
body {
background: linear-gradient(var(--bg-angle), var(--bg-color-1), var(--bg-color-2));
transition: background 0.5s ease;
}
setInterval(() => {
document.documentElement.style.setProperty('--bg-angle',
`${Math.floor(Math.random() * 360)}deg`);
}, 2000);
这些方法可根据项目需求单独使用或组合使用,通过调整动画时间、颜色和运动参数可获得不同的视觉效果。现代CSS特性如mix-blend-mode和filter可进一步丰富动态背景的表现力。







