1. 程式人生 > >如何用純 CSS 創作一個冒著熱氣的咖啡杯

如何用純 CSS 創作一個冒著熱氣的咖啡杯

效果預覽

線上演示

按下右側的“點選預覽”按鈕在當前頁面預覽,點選連結全屏預覽。


https://codepen.io/zhang-ou/pen/xjXxoz


可互動視訊教程


此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。


請用 chrome, safari, edge 開啟觀看。


https://scrimba.com/c/cBm4eU9


原始碼下載


本地下載

請從 github 下載。


https://github.com/comehope/front-end-daily-challenges/tree/master/013-hot-coffee-cup


程式碼解讀


定義 dom,一個名為 coffee 的容器,其中包含一個名為 cup 的元素:

<div class="coffee">
    <div class="cup"></div>
</div>

居中顯示:

html, body {
    height: 100%;
    align-items: center;
    justify-content: center;
    background-color: brown;
}

畫出杯子主體:

.coffee .cup {
    width: 10em;
    height: 9em;
    background-color: white;
    border-bottom-left-radius: 1.5em;
    border-bottom-right-radius: 1.5em;
}

用偽元素畫出杯口:

.coffee .cup {
    position: relative;
}

.coffee .cup::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 2em;
    background-color: chocolate;
    border: 0.5em solid white;
    box-sizing: border-box;
    border-radius: 50%;
    top: -1em;
    box-shadow: inset 0 0 1em rgba(0, 0, 0, 0.5);
}

用偽元素畫出杯子把手:

.coffee .cup::after {
    content: '';
    position: absolute;
    width: 3em;
    height: 3.5em;
    border: 0.8em solid white;
    border-radius: 50%;
    top: 20%;
    left: 80%;
}

dom 元素增加托盤:

<div class="coffee">
    <div class="cup"></div>
    <div class="plate"></div>
</div>

畫出托盤:

.coffee {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: calc(9em + 1em);
    position: relative;
}

.coffee .plate {
    width: 16em;
    height: 1em;
    background-color: white;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;
    position: absolute;
    bottom: -1px;
}

dom 元素增加杯中冒出的熱氣:

<div class="coffee">
    <div class="vapor">
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
    </div>
    <div class="cup"></div>
    <div class="plate"></div>
</div>

畫出杯中冒出的熱氣:

.coffee {
    height: calc(9em + 1em + 2em);
}

.coffee .vapor {
    width: 7em;
    display: flex;
    justify-content: space-between;
}

.coffee .vapor span {
    width: 0.1em;
    min-width: 1px;
    height: 2em;
    background-color: white;
}

定義熱氣冒出的動畫:

.coffee .vapor span {
    animation: evaporation 2s linear infinite;
    filter: opacity(0);
}

@keyframes evaporation {
    from {
        transform: translateY(0);
        filter: opacity(1) blur(0.2em);
    }

    to {
        transform: translateY(-4em);
        filter: opacity(0) blur(0.4em);
    }
}

最後,調整每條熱氣的延遲時間,使動感更強:

.coffee .vapor span:nth-child(1) {
    animation-delay: 0.5s;
}

.coffee .vapor span:nth-child(2) {
    animation-delay: 0.1s;
}

.coffee .vapor span:nth-child(3) {
    animation-delay: 0.3s;
}

.coffee .vapor span:nth-child(4) {
    animation-delay: 0.4s;
}

.coffee .vapor span:nth-child(5) {
    animation-delay: 0.2s;
}

大功告成!

知識點

原文地址:https://segmentfault.com/a/1190000014734039