前端每日實戰:49# 視頻演示如何用純 CSS 創做一支誘人的冰棍

圖片描述

效果預覽

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

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

可交互視頻教程

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

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

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

源代碼下載

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

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

代碼解讀

定義 dom,容器中包含 2 個元素:flex

<div class="ice-lolly">
    <div class="flavors"></div>
    <div class="stick"></div>
</div>

居中顯示:動畫

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: darkslategray;
}

繪製出冰棍的外形:spa

.flavors {
    width: 19em;
    height: 26em;
    font-size: 10px;
    border-radius: 8em 8em 1em 1em;
}

給冰棍上色:

.flavors {
    position: relative;
    overflow: hidden;
}

.flavors::before {
    content: '';
    position: absolute;
    width: 140%;
    height: 120%;
    background: linear-gradient(
        hotpink 0%,
        hotpink 25%,
        deepskyblue 25%,
        deepskyblue 50%,
        gold 50%,
        gold 75%,
        lightgreen 75%,
        lightgreen 100%);
    z-index: -1;
    left: -20%;
    transform: rotate(-25deg);
}

來一點光照效果:

.flavors::after {
    content: '';
    position: absolute;
    width: 2em;
    height: 17em;
    background-color: rgba(255, 255, 255, 0.5);
    left: 2em;
    bottom: 2em;
    border-radius: 1em;
}

畫出冰棍筷子:

.stick {
    position: relative;
    width: 6em;
    height: 8em;
    background-color: sandybrown;
    left: calc(50% - 6em / 2);
    border-radius: 0 0 3em 3em;
}

給冰棍筷子加一點陰影,增長立體感:

.stick::after {
    content: '';
    position: absolute;
    width: inherit;
    height: 2.5em;
    background-color: sienna;
}

讓冰棍的色彩滾動起來:

.flavors::before {
    animation: moving 100s linear infinite;
}

@keyframes moving {
    to {
        background-position: 0 1000vh;
    }
}

最後,增長交互效果,當鼠標懸停時才播放動畫:

.flavors::before {
    animation-play-state: paused;
}

.ice-lolly:hover .flavors::before {
    animation-play-state: running;
}

大功告成!

相關文章
相關標籤/搜索