前端每日實戰:60# 視頻演示如何用純 CSS 創做一塊樂高積木

圖片描述

效果預覽

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

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

可交互視頻

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

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

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

源代碼下載

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

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

代碼解讀

定義 dom,容器中包含一組 3 個面:ide

<div class="brick">
    <div class="sides">
        <span class='front'></span>
        <span class='right'></span>
        <span class="top"></span>
    </div>
</div>

居中顯示:flex

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: radial-gradient(circle at center, white, skyblue);
}

定義容器尺寸:spa

.brick {
    width: 40em;
    height: 30em;
    font-size: 10px;
}

畫出積木的正面:

.brick {
    position: relative;
}

.sides .front {
    position: absolute;
    width: 9em;
    height: 6.8em;
    background-color: #237fbd;
    top: 19em;
    left: 7em;
}

畫出積木的右面:

.sides > * {
    position: absolute;
    background-color: #237fbd;
}

.sides .right {
    width: 18em;
    height: 6.8em;
    filter: brightness(0.8);
    top: 19em;
    left: calc(7em + 9em);
}

畫出積木的頂面:

.sides .top {
    width: 18em;
    height: 10.4em;
    filter: brightness(1.2);
    top: calc(19em - 10.4em);
    left: calc(7em + 9em);
}

把以上 3 個面組合成立方體:

.sides .front {
    transform-origin: right;
    transform: skewY(30deg);
}

.sides .right {
    transform-origin: left;
    transform: skewY(-30deg);
}

.sides .top {
    transform-origin: left bottom;
    transform: rotate(-60deg) skewY(30deg);
}

接下來畫積木的凸粒。

在 dom 中增長 8 個凸粒元素:

<div class="brick">
    <div class="sides">
        <span class='front'></span>
        <span class='right'></span>
        <span class="top"></span>
    </div>
    <div class="studs">
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
    </div>
</div>

定義變量:

.studs span:nth-child(1) {
    --n: 1;
}

.studs span:nth-child(3) {
    --n: 3;
}

.studs span:nth-child(5) {
    --n: 5;
}

.studs span:nth-child(7) {
    --n: 7;
}

.studs span:nth-child(2) {
    --n: 2;
}

.studs span:nth-child(4) {
    --n: 4;
}

.studs span:nth-child(6) {
    --n: 6;
}

.studs span:nth-child(8) {
    --n: 8;
}

畫出左側的凸粒:

.studs span:nth-child(odd) {
    top: calc(4.6em + (var(--n) - 1) / 2 * 2.6em);
    left: calc(23.3em - (var(--n) - 1) / 2 * 4.6em);
}

畫出右側的凸粒:

.studs span:nth-child(even) {
    top: calc(6.9em + (var(--n) - 2) / 2 * 2.6em);
    left: calc(27.9em - (var(--n) - 2) / 2 * 4.6em);
}

最後,畫出凸粒的頂面:

.studs span::before {
    content: '';
    position: absolute;
    width: inherit;
    height: 2em;
    background-color: #4cb7ff;
    border-radius: 50%;
}

大功告成!

相關文章
相關標籤/搜索