前端每日實戰:157# 視頻演示如何用純 CSS 創做一個棋盤錯覺動畫

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。css

https://codepen.io/comehope/pen/VEyoGjhtml

可交互視頻

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。前端

請用 chrome, safari, edge 打開觀看。git

https://scrimba.com/p/pEgDAM/cppKmsdgithub

源代碼下載

每日前端實戰系列的所有源代碼請從 github 下載:chrome

https://github.com/comehope/front-end-daily-challengesdom

代碼解讀

定義 dom,容器中包含 10 個子元素,每一個子元素表示一行:flex

<div class="container">
    <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;
}

定義容器尺寸,用 vmin 單位,並讓子元素豎向排列:spa

.container {
    width: 100vmin;
    height: 100vmin;
    display: flex;
    flex-direction: column;
}

設置子元素的背景圖案爲間隔的黑白色塊,頂部有一條細線:

.container span {
    width: inherit;
    height: 10vmin;
    background: 
        linear-gradient(
            gray, gray 0.5vmin,
            transparent 0.5vmin, transparent
        ),
        repeating-linear-gradient(
            to right,
            black, black 10vmin,
            transparent 10vmin, transparent 20vmin
        )
}

在容器底部補一條細線:

.container {
    border-bottom: 0.5vmin solid gray;
}

增長動畫效果,讓奇數行的背景向右移動半個色塊的位置,移動以後看起來好像奇數行右寬左窄,偶數行左寬右窄,這是一種錯覺:

.container span:nth-child(odd) {
    animation: move 5s linear infinite;
}

@keyframes move {
    0%, 55%, 100% {
        background-position: 0 0;
    }

    5%, 50% {
        background-position: 5vmin 0;
    }
}

讓偶數行的背景也移動起來,產生相反方向的錯覺:

.container span:nth-child(even) {
    animation: move 5s linear infinite reverse;
}

大功告成!

相關文章
相關標籤/搜索