1. 程式人生 > >如何用純 CSS 創作一個容器厚條紋邊框特效

如何用純 CSS 創作一個容器厚條紋邊框特效

效果預覽

線上演示

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

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

可互動視訊教程

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

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

https://scrimba.com/c/cPvn6tE

原始碼下載

本地下載

請從 github 下載。


https://github.com/comehope/front-end-daily-challenges/tree/master/003-diagonal-stripe-border-effects


程式碼解讀


定義一個名為 box 的容器:

<div class="box">
</div>

內容居中顯示:

html,
body {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

畫條紋背景:

.box {
    width: 300px;
    height: 300px;
    background: linear-gradient(
        -45deg,
        white 0%,
        white 25%,
        hotpink 25%,
        hotpink 50%,
        white 50%,
        white 75%,
        hotpink 75%,
        hotpink 100%);
    background-size: 10%;
}

在 box 容器內定義一個名為 content 的容器:

<div class="box">
    <div class="content">
    </div>
</div>

box 容器留出厚邊框,content 容器嵌在其中:

.box .content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.box {
    box-sizing: border-box;
    padding: 15px;
}

.box .content {
    background-color: white;
}

設定厚邊框的立體效果:

.box,
.box .content {
    box-shadow: 0 0 2px deeppink,
                0 0 5px rgba(0, 0, 0, 1),
                inset 0 0 5px rgba(0, 0, 0, 1);
    border-radius: 10px;
}

content 容器中增加內容:

<div class="box">
    <div class="content">
        <h2>What is Lorem Ipsum?</h2>
        <p>Mauris volutpat risus quis nisi tempus hendrerit. Nullam nisi urna, suscipit quis risus sed, congue congue quam. Morbi sit amet suscipit ex. Vivamus vel nulla ac libero volutpat ultrices.</p>
    </div>
</div>

內容佈局:

.box .content {
    flex-direction: column;
    box-sizing: border-box;
    padding: 30px;
    text-align: center;
    font-family: sans-serif;
}

.box .content h2 {
    color: deeppink;
}

.box .content p {
    color: dimgray;
}

定義動畫效果:

@keyframes animate {
    from {
        background-position: 0;
    }

    to {
        background-position: 10%;
    }
}

最後,把動畫效果應用到 box 容器上:

.box {
    animation: animate 2s linear infinite;
}

大功告成!

知識點

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