介紹一個利用css3和虛擬元素實現滑鼠移入時底線向兩邊展開的特效代碼

來源:互聯網
上載者:User
這篇文章主要介紹了利用css3+虛擬元素實現滑鼠移入時底線向兩邊展開效果的相關資料,文中先進行了詳細的介紹,方便大家理解,而後給出了完整的執行個體代碼讓大家可以參考學習,需要的朋友們下面來一起學習學習吧。

先來看看:

實現思路:

將虛擬元素:before和:after定位到元素底部中間,設定寬度從0變成100%達到目的。

實現方法:

1、首先定義一個塊狀元素(行內元素沒有寬高)並修改樣式為一個背景色為淺灰色的矩形,設定相對定位。

html代碼

<p id="underline"></p>

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{/*動畫效果是從中間向左延伸至50%的寬度*/    left:0%;     width:50%;}#underline:hover:after{/*動畫效果是從中間向右延伸至50%的寬度*/    left: 50%; /*這句多餘,主要是為了對照*/    width: 50%;}

最佳化

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:50%變成0%的同時,寬度從0%變成100%*/    left: 0%;    width: 100%;}

2、只定義:after虛擬元素,將其從距離左邊50%寬度為0的同時改變成距離左邊0%寬度為100%就可以實現,從而達到了精簡代碼的目的,而且還多餘出了:before方便進行別的操作。

完整代碼

<!DOCTYPE html><html lang="en"><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>    <p id="underline"></p></body></html>
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.