https://github.com/comehope/front-end-daily-challenges
定义 dom,容器中包含 15 个元素:
<div class="flag"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div>
居中显示:
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background-color: black; }
定义容器尺寸:
.flag { width: 10em; height: 15em; font-size: 20px; }
设置线条样式:
.flag span { width: 0.25em; height: inherit; background-color: deepskyblue; }
让线条平铺:
.flag { display: flex; justify-content: space-between; }
增加 3d 透视效果:
.flag { transform: perspective(500px) rotateY(-20deg); }
定义左右移动的动画效果:
.flag span { animation: wave 1.5s ease-in-out infinite alternate; } @keyframes wave { to { transform: translateX(2em); } }
设置元素变量值:
.flag span:nth-child(1) { --n: 1; } .flag span:nth-child(2) { --n: 2; } /* 共 15 个元素,每元素的 --n 变量值等于它的序号。 */ /* 中间代码略 …… */ .flag span:nth-child(14) { --n: 14; } .flag span:nth-child(15) { --n: 15; }
让各线条分别延时启动动画,形成旗帜飘扬的效果:
.flag span { animation-delay: calc(var(--n) * -0.1s); }
最后,增加光影效果:
.flag span { background-color: ghostwhite; } @keyframes wave { to { transform: translateX(2em); background-color: deepskyblue; } }
大功告成!