前端每日實戰:161# 視頻演示如何用純 CSS 創作一張紀念卓別林的卡片(沒有笑聲的一天就是被荒廢的一天)

圖片描述

效果預覽

按下右側的“點擊預覽”按鈕可以在當前頁面預覽,點擊鏈接可以全屏預覽。

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

可交互視頻

此視頻是可以交互的,你可以隨時暫停視頻,編輯視頻中的代碼。

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

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

源代碼下載

每日前端實戰系列的全部源代碼請從 github 下載:

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

代碼解讀

定義 dom,容器中包含的 3 個元素分別代表帽子、鬍鬚和手杖:

<figure class="chaplin">
    <span class="hat"></span>
    <span class="beard"></span>
    <span class="stick"></span>
</figure>

居中顯示:

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

定義容器尺寸,並設置子元素水平居中:

.chaplin {
    width: 40em;
    height: 30em;
    font-size: 10px;
    background-color: #eee;
    box-shadow: 0 0 3em rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: column;
    align-items: center;
}

定義默認顏色,後面用 currentColor 引用此顏色:

.chaplin {
    color: #555;
}

畫出帽子的輪廓:

.chaplin {
    position: relative;
}

.hat {
    position: absolute;
    width: 6.4em;
    height: 4.6em;
    background-color: currentColor;
    border-radius: 2.3em 2.3em 0 0;
    top: 1.4em;
}

用僞元素畫出帽沿:

.hat::before {
    content: '';
    position: absolute;
    width: 10em;
    height: 0.8em;
    background-color: currentColor;
    border-radius: 0.4em;
    top: calc(100% + 0.4em);
    left: calc((100% - 10em) / 2);
}

畫出鬍子:

.beard {
    position: absolute;
    width: 1.5em;
    height: 0;
    top: 11.6em;
    border: solid transparent;
    border-width: 0 0.4em 1em 0.4em;
    border-bottom-color: currentColor;
}

畫出手杖的杖杆:

.stick {
    position: absolute;
    width: 0.8em;
    height: 10.5em;
    background-color: currentColor;
    bottom: 0;
}

::before 僞元素畫出手杖的握柄:

.stick::before {
    content: '';
    position: absolute;
    box-sizing: border-box;
    width: 5.6em;
    height: 3em;
    border: 0.8em solid;
    border-radius: 5.6em 5.6em 0 0;
    border-bottom: none;
    top: -3em;
}

::after 僞元素修飾握柄的端點,使其圓潤自然:

.stick::after {
    content: '';
    position: absolute;
    width: 0.8em;
    height: 0.8em;
    background-color: currentColor;
    border-radius: 50%;
    left: calc(5.6em - 0.8em);
    top: -0.4em;
}

使手杖水平居中:

.stick {
    left: calc((100% - (5.6em - 0.8em)) / 2);
}

至此,抽象的卓別林形象完成,接下來排版一句他的名言。
在 dom 中增加一個 .quote 元素,並把一句話分爲 3 段:

<figure class="chaplin">
    <span class="hat"></span>
    <span class="beard"></span>
    <span class="stick"></span>
    <p class="quote">
        <span>a day without</span>
        <span>laughter</span>
        <span>is a day wasted</span>
    </p>
</figure>

定位文字,並豎排 3 段文字:

.quote {
    position: absolute;
    left: 50%;
    bottom: 2.5em;
    font-family: sans-serif;
    text-transform: uppercase;
    font-weight: bold;
    display: flex;
    flex-direction: column;
}

調整字號和字間距,使 3 段文字對齊:

.quote span:nth-child(1) {
    letter-spacing: 0.05em;
}

.quote span:nth-child(2) {
    font-size: 1.6em;
}

大功告成!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章