6 种超链接效果(上)

介绍 CSS 如何让超链接变得更加生动和精彩
1. 滑动背景效果
这个效果使用css 的 box-shadow 属性创造一个滑动背景动画效果,废话不多说,直接上css:
1
2
3
4
5
6
7
8
9
10
11
a {
box-shadow: inset 0 0 0 0 #54b3d6;
color: #54b3d6;
margin: 0 -.25rem;
padding: 0 .25rem;
transition: color .3s ease-in-out, box-shadow .3s ease-in-out;
}
a:hover {
box-shadow: inset 100px 0 0 0 #54b3d6;
color: white;
}
首先指定超链接未点击之前的 box-shadow ,并使用 transition 指定一个专场动画,然后使用 a:hover 指定鼠标放上去的最终效果。最后的效果看上去就像这样子:
2. 文字替换效果
先说一下最终的结果吧:当鼠标停留到超链接上时,会使用一个动画效果吧当前的文字替换为想要的文字。而这个转换之后的文字可以使用 data-attribute 属性去指定。
首先,来看看html代码:
1
<a href="#" class="swappinlink" data-replace="看看"><span>前往</span></a>
这里我们需要用到两个伪元素: before 和 after,目的是为了指定动作前后的一些CSS属性。
1
2
3
4
5
6
7
a::before,
a::after {
content: '';
position: absolute;
width: 100%;
left: 0;
}
上面指定了::before 和 ::after 两个伪元素的 context 为空,然后指定a::after的 context 就是上面html代码里面的 data-replace属性:
1
2
3
4
5
6
a::after {
content: attr(data-replace);
top: 0;
transform-origin: 100% 50%;
transform: translate3d(200%, 0, 0);
}
其中::after也同样指定了 transform 属性,这样在超链接被渲染之后 content 里面的内容也容易在 x 轴中移动了2倍的距离,然后通过 hover 和 focus 的伪元素把 content 内容转移到正确的位置上来:
1
2
3
4
a:hover::after,
a:focus::after {
transform: translate3d(0, 0, 0);
}
不多说,咱们来看看最终的效果吧:
3. 背景覆盖效果
这个效果的原理也很简单,使用::before伪元素在超链接底部生成一定高度的下划线,然后使用:hover::before伪元素把整个下划线的高度设置伪 100% , 中间使用 transition 设置一些动画效果即可:
1
2
3
4
a {
text-decoration: none;
position: relative;
}
去掉默认的下划线属性,然后设置 ::before 属性:
1
2
3
4
5
6
7
8
9
10
11
a::before {
content: '';
background-color: hsla(196, 61%, 58%, .75);
position: absolute;
left: 0;
bottom: 3px;
width: 100%;
height: 8px;
z-index: -1;
transition: all .3s ease-in-out;
}
最后一行是动画效果。最后设置一下 hover 之后的效果:
1
2
3
4
a:hover::before {
bottom: 0;
height: 100%;
}
那么,这就大功告成,来看看最后的效果吧:
好了,今天就写到这里,下期再见。另外代码已在这里准备好,欢迎下载 讨论+学习。