天天看點

如何用純 CSS 創作一個蝴蝶标本展示框

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/w178191520/article/details/84392916

效果預覽

線上示範

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

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

可互動視訊教程

此視訊是可以互動的,你可以随時暫停視訊,編輯視訊中的代碼。

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

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

源代碼下載下傳

本地下載下傳

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

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

代碼解讀

定義 dom,容器表示整隻蝴蝶,因為蝴蝶是對稱的,是以分為左右兩邊,每邊有 3 個子元素:

<div class="butterfly">
    <div class="left">
        <span></span>
        <span></span>
        <span></span>
    </div>
    <div class="right">
        <span></span>
        <span></span>
        <span></span>
    </div>
</div>
           

居中顯示:

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(gray, lightyellow, gray);
}
           

定義蝴蝶的尺寸:

.butterfly {
    position: relative;
    width: 10em;
    height: 10em;
}
           

先畫左半邊:

.butterfly .left {
    position: absolute;
    width: inherit;
    height: inherit;
}
           

用第 1 個子元素畫出翅膀的上半部分:

.butterfly span {
    position: absolute;
    border-radius: 50%;
}

.butterfly span:nth-child(1) {
    width: 5em;
    height: 7em;
    background-color: gold;
}
           

用第 2 個子元素畫出翅膀的下半部分:

.butterfly span:nth-child(2) {
    width: 5.5em;
    height: 3.5em;
    background-color: orangered;
    top: 5em;
    left: -2.5em;
    filter: opacity(0.6);
}
           

用第 3 個子元素畫出觸角:

.butterfly span:nth-child(3) {
    width: 6em;
    height: 6em;
    border-right: 0.3em solid orangered;
    top: -0.5em;
}
           

把左半邊複制一份到右半邊:

.butterfly .right {
    position: absolute;
    width: inherit;
    height: inherit;
}

.butterfly .right {
    transform: rotateY(180deg) rotate(-90deg);
    top: 0.4em;
    left: 0.4em;
}
           

把标本裝到展示框裡:

.butterfly::before {
    content: '';
    position: absolute;
    box-sizing: border-box;
    top: -2.5em;
    left: -8em;
    width: 24em;
    height: 18em;
    background-color: black;
      border: 0.2em inset silver;
}

.butterfly::after {
    content: '';
    position: absolute;
    box-sizing: border-box;
    width: 40em;
    height: 30em;
    background-color: lightyellow;
    top: -9em;
    left: -16em;
    border: 2em solid burlywood;
    border-radius: 3em;
    box-shadow: 
        0 0.3em 2em 0.4em rgba(0, 0, 0, 0.3),
        inset 0.4em 0.4em 0.1em 0.5em rgba(0, 0, 0, .4);
    z-index: -1;
}
           

最後,調整一下因圖案傾斜引起的位移:

.butterfly {
    transform: translateX(1em);
}
           

大功告成!

原文位址:https://segmentfault.com/a/1190000015236585

繼續閱讀