思路
将伪元素:before和:after定位到元素底部中间,设置宽度从0变成100%达到目的。
实现过程:
下面是我实现某官网首页导航中a链接时做的简单特效的过程。须知:a链接是行(内)元素,而行元素是没有width的!
所以,我们要实现题目所说特效,就要为每个a标签嵌套一个“盒子”——div最好(因为它最“干净”)
当然,如果你实现的是列表(li)的话,把它
display:block;
或
display:inline-block;
即可。
比如这样:
<div id="underline">
<a href="#">云小梦</a>
</div>
#underline{
width: 110px;
height: 50px;
margin: 20px;
position: relative;
}
#underline>a{
color: lightgrey;
text-decoration: none;
/* 必须有下面这三行:这可以让此“div”移到父级的中央(而不是中心与中心重合) */
position: absolute;
top: 50%;
left: 50%;
cursor: pointer;
/* 然后再去位移 —— 上面往哪偏,这里往回移。 (正百分比是往右、下) */
transform: translate(-50%,-50%);
}
#underline:after{
content: "";
width: 0;
height: 2px;
background: rgb(255,170,0);
position: absolute;
top: 100%;
left: 50%;
transition: all .5s;
}
#underline:hover:after{
left: 0;
width: 100%;
}