伪元素实现鼠标移入下划线向两边展开效果

【原理】  

   将伪元素:before和:after定位到元素底部中间,设置宽度从0变成100%达到目的。

【案例】

   首先定义一个块状元素(行内元素没有宽高)并修改样式为一个背景色为浅灰色的矩形,设置相对定位

<div id="underline"></div>
#underline{
    width: 200px;
    height: 50px;
    background: #ddd;
    margin: 20px;
    position: relative;
}

2、设置:before和:after两个伪元素,将其设置为背景色为蓝色(也就是下划线的颜色),利用绝对定位将两个元素固定到#underline底部中间位置

#underline:before,
#underline:after{
    content: "";/*单引号双引号都可以,但必须是英文*/
    width: 0;
    height: 3px; /*下划线高度*/
    background: blue; /*下划线颜色*/
    position: absolute;
    top: 100%;
    left: 50%;
    transition: all .8s ; /*css动画效果,0.8秒完成*/
}

3、设置鼠标移入效果

#underline:hover:before{/*动画效果是从中间向左延伸至50%的宽度*/
    left:0%;
    width:50%;
}
#underline:hover:after{/*动画效果是从中间向右延伸至50%的宽度*/
    left: 50%; /*这句多余,主要是为了对照*/
    width: 50%;
}

【优化】

  1、虽然目的达到了,但是用了两个伪元素,一个向左延伸50%,一个向右延伸50%,只用一个延伸至100%能否达到目的呢?

#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>
    <div id="underline"></div>
</body>
</html>

.

猜你喜欢

转载自570109268.iteye.com/blog/2411832