css 动画制作星星
使用CSS动画制作星星
方法一:使用纯CSS创建五角星
通过CSS的clip-path属性可以创建五角星形状,结合动画实现闪烁效果。

.star {
width: 50px;
height: 50px;
background-color: gold;
clip-path: polygon(
50% 0%,
61% 35%,
98% 35%,
68% 57%,
79% 91%,
50% 70%,
21% 91%,
32% 57%,
2% 35%,
39% 35%
);
animation: twinkle 1s infinite alternate;
}
@keyframes twinkle {
from { opacity: 0.3; }
to { opacity: 1; }
}
方法二:使用伪元素创建复杂星星
通过::before和::after伪元素叠加,实现更丰富的星星效果。

.star-2 {
position: relative;
width: 0;
height: 0;
border-right: 25px solid transparent;
border-bottom: 17px solid gold;
border-left: 25px solid transparent;
transform: rotate(35deg);
}
.star-2::before {
content: '';
position: absolute;
top: -11px;
left: -26px;
width: 0;
height: 0;
border-right: 25px solid transparent;
border-bottom: 17px solid gold;
border-left: 25px solid transparent;
transform: rotate(-70deg);
}
.star-2::after {
content: '';
position: absolute;
top: 0;
left: -25px;
width: 0;
height: 0;
border-right: 25px solid transparent;
border-bottom: 17px solid gold;
border-left: 25px solid transparent;
transform: rotate(-35deg);
}
方法三:旋转动画实现星光效果
通过旋转和缩放变换创建动态星光。
.shining-star {
width: 30px;
height: 30px;
background: radial-gradient(circle, gold 40%, transparent 50%);
animation: shine 2s ease-in-out infinite;
}
@keyframes shine {
0% { transform: scale(1) rotate(0deg); }
50% { transform: scale(1.2) rotate(180deg); }
100% { transform: scale(1) rotate(360deg); }
}
方法四:多星星随机动画
创建多个星星并应用不同的动画延迟。
.star-group {
display: flex;
gap: 20px;
}
.star-item {
width: 20px;
height: 20px;
background-color: gold;
clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
animation: pulse 1.5s infinite;
}
.star-item:nth-child(2) { animation-delay: 0.3s; }
.star-item:nth-child(3) { animation-delay: 0.6s; }
@keyframes pulse {
0%, 100% { transform: scale(1); opacity: 0.7; }
50% { transform: scale(1.3); opacity: 1; }
}
注意事项
- 浏览器兼容性:
clip-path属性在现代浏览器中支持良好,但在旧版IE中不兼容 - 性能优化:减少同时运行的复杂动画数量,避免页面卡顿
- 响应式设计:使用相对单位(如vw、em)使星星尺寸适应不同屏幕
- 颜色选择:可以使用CSS变量方便地调整星星颜色
这些方法可以单独使用,也可以组合创造出更复杂的星空效果。通过调整动画参数如持续时间、延迟和关键帧,可以实现各种不同的视觉效果。






