最近關注了油管上的 CSS Animation Effects Tutorial 系列,裏面介紹了很是多有意思的 CSS 動效。其中第一個就是很酷炫的霓虹燈效果,這裏就實現思路作一個簡單的記錄和分享。
這是要實現的效果:css
能夠看到,在鼠標移入按鈕的時候,會產生相似霓虹燈光的效果;在鼠標移出按鈕的時候,會有一束光沿着固定的軌跡(按鈕外圍)運動。html
霓虹燈光的實現比較簡單,用多重陰影來作便可。咱們給按鈕加三層陰影,從內到外每層陰影的模糊半徑遞增,這樣的多個陰影疊加在一塊兒,就能夠造成一個相似霓虹燈光的效果。這段的代碼以下:動畫
HTML:spa
<div class="light"> Neon Button </div>
CSS:code
body { background: #050901; } .light { width: fit-content; padding: 25px 30px; color: #03e9f4; font-size: 24px; text-transform: uppercase; transition: 0.5s; letter-spacing: 4px; cursor: pointer; } .light:hover { background-color: #03e9f4; color: #050801; box-shadow: 0 0 5px #03e9f4, 0 0 25px #03e9f4, 0 0 50px #03e9f4, 0 0 200px #03e9f4; }
最終的效果以下:orm
雖然看起來只有一個光束沿着按鈕的邊緣運動,但實際上這是四個光束沿着不一樣方向運動以後疊加的效果。它們運動的方向分別是:從左往右、從上往下、從右往左、從下往上,以下圖所示:htm
在這個過程當中,光束和光束之間產生了交集,若是隻看按鈕的邊緣部分,就很像是隻有一個光束在作順時針方向的運動。圖片
下面是具體實現中幾個須要注意的點:ci
div.light
的四個子 div,初始位置分別是在按鈕的最左側、最上方、最右側和最下方,並按照固定的方向作重複的運動div.light
設置一個溢出隱藏代碼以下:element
HTML:
<div class="light"> <div></div> <div></div> <div></div> <div></div> Neon Button </div>
CSS:
.light { position: relative; padding: 25px 30px; color: #03e9f4; font-size: 24px; text-transform: uppercase; transition: 0.5s; letter-spacing: 4px; cursor: pointer; overflow: hidden; } .light:hover { background-color: #03e9f4; color: #050801; box-shadow: 0 0 5px #03e9f4, 0 0 25px #03e9f4, 0 0 50px #03e9f4, 0 0 200px #03e9f4; } .light div { position: absolute; } .light div:nth-child(1){ width: 100%; height: 2px; top: 0; left: -100%; background: linear-gradient(to right,transparent,#03e9f4); animation: animate1 1s linear infinite; } .light div:nth-child(2){ width: 2px; height: 100%; top: -100%; right: 0; background: linear-gradient(to bottom,transparent,#03e9f4); animation: animate2 1s linear infinite; animation-delay: 0.25s; } .light div:nth-child(3){ width: 100%; height: 2px; bottom: 0; right: -100%; background: linear-gradient(to left,transparent,#03e9f4); animation: animate3 1s linear infinite; animation-delay: 0.5s; } .light div:nth-child(4){ width: 2px; height: 100%; bottom: -100%; left: 0; background: linear-gradient(to top,transparent,#03e9f4); animation: animate4 1s linear infinite; animation-delay: 0.75s; } @keyframes animate1 { 0% { left: -100%; } 50%,100% { left: 100%; } } @keyframes animate2 { 0% { top: -100%; } 50%,100% { top: 100%; } } @keyframes animate3 { 0% { right: -100%; } 50%,100% { right: 100%; } } @keyframes animate4 { 0% { bottom: -100%; } 50%,100% { bottom: 100%; } }
這樣就能夠達到文章開頭圖片的效果了。
若是想要其它顏色的霓虹燈光效果怎麼辦呢?是否須要把相關的顏色從新修改一遍?其實咱們有更簡單的方法,就是使用 filter:hue-rotate(20deg)
一次性修改 div.light
和內部全部元素的色相/色調。
The
hue-rotate()
CSS function rotates the hue of an element and its contents.
最終效果以下: