利用偽元素和CSS3實現滑鼠移入下劃線向兩邊展開效果
阿新 • • 發佈:2019-02-13
一、思路:
將偽元素:before和:after定位到元素底部中間,設定寬度從0變成100%達到目的。
二、實現:
1、首先定義一個塊狀元素(行內元素沒有寬高)並修改樣式為一個背景色為淺灰色的矩形,設定相對定位。
HTML程式碼
<div id="underline"></div>
CSS樣式
#underline{ width: 200px; height: 50px; background: #ddd; margin: 20px; position: relative; }
2、設定:before和:after兩個偽元素,將其設定為背景色為藍色(也就是下劃線的顏色),利用絕對定位將兩個元素固定到#underline底部中間位置。
CSS樣式
#underline:before, #underline:after{ content: "";/*單引號雙引號都可以,但必須是英文*/ width: 0; height: 3px; /*下劃線高度*/ background: blue; /*下劃線顏色*/ position: absolute; top: 100%; left: 50%; transition: all .8s ; /*css動畫效果,0.8秒完成*/ }
3、設定滑鼠移入效果。
CSS樣式
#underline:hover:before{ left:0%; width:50%; } #underline:hover:after{ left: 50%; /*這句多餘,主要是為了對照*/ width: 500%; }
三:優化
1、雖然目的達到了,但是用了兩個偽元素,一個向左延伸50%,一個向右延伸50%,只用一個延伸至100%能否達到目的呢?
CSS程式碼
#underline:after{ content: ""; width: 0; height: 5px; background: blue; position: absolute; top: 100%; left: 50%; transition: all .8s; } #underline:hover:after{ left: 0%; width: 100%; }
四、完整程式碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>滑鼠移入下劃線展開</title> <style type="text/css"> #underline{ width: 200px; height: 50px; background: #ddd; margin: 20px; position: relative; } #underline:after{ content: ""; width: 0; height: 5px; background: blue; position: absolute; top: 100%; left: 50%; transition: all .8s; } #underline:hover:after{ left: 0%; width: 100%; } </style> </head> <body> <div id="underline"></div> </body> </html>
2、只定義:after偽元素,將其從距離左邊50%寬度為0的同時改變成距離左邊0%寬度為100%就可以實現,從而達到了精簡程式碼的目的,而且還多餘出了:before。