如何用純 CSS 創作在文字前後穿梭的邊框
阿新 • • 發佈:2018-11-24
效果預覽
線上演示按下右側的“點選預覽”按鈕可以在當前頁面預覽,點選連結可以全屏預覽。
https://codepen.io/comehope/pen/qYepNv
可互動視訊教程
此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。
請用 chrome, safari, edge 開啟觀看。
https://scrimba.com/p/pEgDAM/cQ73Vt8
原始碼下載
線上下載每日前端實戰系列的全部原始碼請從 github 下載:
https://github.com/comehope/front-end-daily-challenges
程式碼解讀
定義 dom,容器中包含文字:
<div class="warning">ERROR 404</div>
居中顯示:
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: rgb(20%, 20%, 20%);
}
定義文字樣式:
.warning { color: whitesmoke; font-size: 100px; font-family: sans-serif; font-weight: bold; }
用偽元素定義邊框尺寸:
.warning {
position: relative;
padding: 0.6em 0.4em;
}
.warning::before,
.warning::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0.2em solid;
box-sizing: border-box;
}
把邊框分為兩部分,拼在一起:
.warning::before, .warning::after { border: 0.2em solid transparent; color: orangered; } .warning::before { border-top-color: currentColor; border-right-color: currentColor; } .warning::after { border-bottom-color: currentColor; border-left-color: currentColor; }
把上邊框和右邊框下沉一層:
.warning::before {
z-index: -1;
}
為下邊框和在邊框加上陰影:
.warning::after {
box-shadow: 0.3em 0.3em 0.3em rgba(20%, 20%, 20%, 0.8);
}
最後,讓邊框轉起來:
.warning::before,
.warning::after {
animation: rotating 10s infinite;
}
@keyframes rotating {
to {
transform: rotate(360deg);
}
}
大功告成!