如何完成悬停过渡?

时间:2019-02-10 12:00:04

标签: html css

我正在尝试从uber.design网站复制此过渡:

I am trying to replicate this transition from uber.design site

问题是我被困于逆转过渡:

.un {
  display: inline-block;
}

.un:after {
  content: '';
  width: 0px;
  height: 2px;
  display: block;
  background: black;
  transition: 300ms;
}

.un:hover:after {
  width: 100%;
<span class="un">Underlined Text</span>

2 个答案:

答案 0 :(得分:3)

您可以使用渐变并延迟调整background-position以获得这种效果:

.un {
  display: inline-block;
  padding-bottom:2px;
  background-image: linear-gradient(#000, #000);
  background-position: 0 100%; /*OR bottom left*/
  background-size: 0% 2px;
  background-repeat: no-repeat;
  transition:
    background-size 0.3s,
    background-position 0s 0.3s; /*change after the size immediately*/
}

.un:hover {
  background-position: 100% 100%; /*OR bottom right*/
  background-size: 100% 2px;
}
<span class="un">Underlined Text</span>

如果要在悬停时连续播放动画,可以尝试以下操作:

.un {
  display: inline-block;
  padding-bottom:2px;
  background-image: linear-gradient(#000, #000);
  background-position: right -100% bottom 0;
  background-size: 200% 2px;
  background-repeat: no-repeat;
}

.un:hover {
  background-position: left -100% bottom 0;
  transition: background-position 0.5s;
}
<span class="un">Underlined Text</span>

您可以检查以下答案以获取有关如何计算不同值的更多详细信息:https://stackoverflow.com/a/51734530/8620333

答案 1 :(得分:2)

您需要将伪元素放置在绝对位置,并使用:not选择器来重现此效果。

.un {
  display: inline-block;
  position: relative;
}

.un:after {
  content: '';
  width: 0px;
  height: 2px;
  position: absolute;
  top: 100%;
  left: 0;
  background: black;
  transition: 300ms;
}

.un:hover:after {
  width: 100%;
}

.un:not(:hover):after {
  right: 0;
  left: auto;
}
<span class="un">Underlined Text</span>