如何使用border-bottom为链接加下划线设置动画,以便链接文本和下划线之间有空格?

时间:2017-06-21 10:25:31

标签: css css3

如何使用border-bottom为链接加下划线设置动画,以便文本和下划线之间有空格?

我知道如何按以下方式执行此操作,以便为默认的text-decoration元素设置动画。但是我希望链接和下划线之间有空格,这就是为什么我认为我需要使用border-bottom。但我无法通过过渡动画获得边框底部的工作。我怎么能这样做?我试图寻找其他解决方案,但无法找到任何解决方案。谢谢!

h2 > a {
  position: relative;
  color: #000;
  text-decoration: none;
}

h2 > a:before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: #000;
  visibility: hidden;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transition: all 0.3s ease-in-out 0s;
  transition: all 0.3s ease-in-out 0s;
}

h2 > a:hover:before {
  visibility: visible;
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}

2 个答案:

答案 0 :(得分:7)

您提供的代码使用的是伪元素,而不是默认的文本修饰。由于伪元素绝对定位,您可以轻松更改距离。将a:before底部更改为-5px或任何负值适合您想要的距离:



a {
  position: relative;
  color: #000;
  text-decoration: none;
}

a:before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: -5px;
  left: 0;
  background-color: #000;
  visibility: hidden;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transition: all 0.3s ease-in-out 0s;
  transition: all 0.3s ease-in-out 0s;
}

a:hover:before {
  visibility: visible;
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}

<a href="#">Long long text</a>
&#13;
&#13;
&#13;

答案 1 :(得分:7)

你可以通过背景和背景大小伪造动画边框:

&#13;
&#13;
a {
  padding-bottom: 5px;
  /* set here size + gap size from text */
  background: linear-gradient(0deg, currentcolor, currentcolor) bottom center no-repeat;
  background-size: 0px 3px;
  transition: 0.5s;
  text-decoration: none;
}

a:hover {
  background-size: 100% 3px;
}

a[class] {
  color: gray;
}

a.tst {
  color: purple;
  background: linear-gradient(0deg, currentcolor, currentcolor) bottom center no-repeat, linear-gradient(0deg, turquoise, turquoise) center calc(100% - 2px) no-repeat;
  background-size: 0px 2px;
}

a.tst:hover {
  background-size: 100% 2px;
}
&#13;
<a href>kake animated border</a>
<a href class> why currentcolor ?</a>
<a href class="tst">mix of colors ?</a>
&#13;
&#13;
&#13;