效果預覽
按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。css
https://codepen.io/comehope/pen/GBzLdyhtml
可交互視頻
此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。前端
請用 chrome, safari, edge 打開觀看。git
https://scrimba.com/p/pEgDAM/cGENVuRgithub
源代碼下載
每日前端實戰系列的所有源代碼請從 github 下載:chrome
https://github.com/comehope/front-end-daily-challengesdom
代碼解讀
定義 dom,容器中包含 10 個元素,每一個元素表明 1 個圓環:佈局
<div class="circles"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div>
居中顯示:flex
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background-color: lightgoldenrodyellow; }
定義容器尺寸和其中子元素的佈局方式:spa
.circles { width: 10em; height: 10em; font-size: 30px; border: 1px dashed black; display: flex; justify-content: center; }
爲每一個圓環定義下標變量:
.circles span:nth-child(1) { --n: 1; } .circles span:nth-child(2) { --n: 2; } .circles span:nth-child(3) { --n: 3; } .circles span:nth-child(4) { --n: 4; } .circles span:nth-child(5) { --n: 5; } .circles span:nth-child(6) { --n: 6; } .circles span:nth-child(7) { --n: 7; } .circles span:nth-child(8) { --n: 8; } .circles span:nth-child(9) { --n: 9; } .circles span:nth-child(10) { --n: 10; }
設置每一個的圓環的尺寸,顏色黑白間隔:
.circles { position: relative; } .circles span { position: absolute; --diameter: calc(10em - (var(--n) - 1) * 1em); width: var(--diameter); height: var(--diameter); border-radius: 50%; } .circles span:nth-child(odd) { background-color: darkred; } .circles span:nth-child(even) { background-color: gold; }
把尺寸最小的 3 個圓環向下移動,造成凹陷的效果:
.circles span:nth-child(n+8) { top: calc((var(--n) - 7) * 1em); }
讓容器旋轉起來,就好像一隻監視的眼睛轉來轉去:
.circles { animation: rotating 5s linear infinite; } @keyframes rotating { to { transform: rotate(1turn); } }
大功告成!