前端每日实战: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;
}

大功告成!

相关文章
相关标签/搜索