前端每日實戰:41# 視頻演示如何創做用純 CSS 繪製一支栩栩如生的鉛筆

圖片描述

效果預覽

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

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

可交互視頻教程

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

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

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

源代碼下載

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

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

代碼解讀

定義dom, 容器中包含筆頭、筆桿(包含文字)和橡皮 3 部分:flex

<div class="pencil">
    <span class="taper"></span>
    <span class="barrel">made in China</span>
    <span class="eraser"></span>
</div>

居中顯示:url

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

定義鉛筆的尺寸:spa

.pencil {
    position: relative;
    width: 50em;
    height: 3.5em;
}

畫出筆桿:

.pencil .barrel {
    position: absolute;
    width: 40em;
    left: 4em;
    background-color: green;
    border-top: 1em solid forestgreen;
    border-bottom: 1em solid darkgreen;
}

設置筆桿上文字的樣式:

.pencil .barrel {
    line-height: 1.5em;
    font-family: sans-serif;
    text-transform: uppercase;
    color: silver;
    text-align: center;
}

用僞元素畫出筆頭:

.pencil .taper::before,
.pencil .taper::after {
    content: '';
    position: absolute;
    left: -4em;
    border-style: solid;
    border-width: calc(3.5em / 2) 4em;
}

.pencil .taper::before {
    border-color: transparent burlywood transparent transparent;
}

.pencil .taper::after {
    border-color: transparent green transparent transparent;
    transform: scale(0.3);
}

畫出橡皮:

.pencil .eraser {
    position: absolute;
    right: 0;
    width: 6em;
    height: 1.5em;
    background-color: lightpink;
    border-top: 1em solid pink;
    border-bottom: 1em solid lightcoral;
    border-top-right-radius: 0.5em;
    border-bottom-right-radius: 0.5em;
}

用僞元素畫出橡皮上的鐵箍:

.pencil .eraser::before {
    content: '';
    position: absolute;
    top: -1em;
    left: 0;
    width: 1.5em;
    height: 1.5em;
    background-color: silver;
    border-top: 1em solid lightgray;
    border-bottom: 1em solid gray;
}

最後,增長陰影:

.pencil {
    filter: drop-shadow(5px 10px 3px gray);
}

大功告成!

相關文章
相關標籤/搜索