前端每日實戰:100# 視頻演示如何用純 CSS 創做閃閃發光的霓虹燈文字

圖片描述

效果預覽

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

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

可交互視頻

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

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

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

源代碼下載

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

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

代碼解讀

定義 dom,容器中的 3 個元素分別表明文本、漸變背景和光影,其中文本還包含一個數據屬性 data-textflex

<div class="neon">
    <span class="text" data-text="thanks">thanks</span>
    <span class="gradient"></span>
    <span class="spotlight"></span>
</div>

居中顯示:動畫

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

設置文字樣式:spa

.text {
    background-color: black;
    color: white;
    font-size: 180px;
    font-weight: bold;
    font-family: sans-serif;
    text-transform: uppercase;
}

用僞元素和數據屬性增長文字,產生描邊效果:

.text::before {
    content: attr(data-text);
    position: absolute;
    color: white;
    filter: blur(0.02em);
}

用混色模式產生描邊效果:

.text::before {
    mix-blend-mode: difference;
}

設置漸變色背景:

.neon {
    position: relative;
}

.gradient {
    position: absolute;
    background: linear-gradient(45deg, red, gold, lightgreen, gold, red);
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

用混色模式把背景做用到文字上:

.gradient {
    mix-blend-mode: multiply;
}

用徑向漸變製做光影背景:

.spotlight {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
        radial-gradient(
            circle,
            white,
            transparent 25%
        ) center / 25% 25%,
        radial-gradient(
            circle,
            white,
            black 25%
        ) center / 12.5% 12.5%;
}

設置光影移動的動畫效果:

.neon {
    overflow: hidden;
}

.spotlight {
    top: -100%;
    left: -100%;
    animation: light 5s linear infinite;
}

@keyframes light {
    to {
        transform: translate(50%, 50%);
    }
}

用混色模式把光影做用到漸變背景上:

.spotlight {
    mix-blend-mode: color-dodge;
}

最後,調高亮度,而且使文字不能被選中:

.neon {
    filter: brightness(200%);
}

.text {
    user-select: none;
}

大功告成!

相關文章
相關標籤/搜索