CSS下划线动画无效

时间:2017-03-08 03:34:44

标签: html css transform

我正在尝试使用CSS中的转换来制作动画。当我将鼠标悬停在链接上时,我正在尝试获取下划线动画。在另一个html文件中,我有类似的代码,它的工作原理;但由于某种原因,这里没有用。当我将鼠标悬停在链接上时,它们会更改为指定的白色但不显示转换。我提供了导航栏HTML和相关的CSS。

ul {
  list-style-type: none;
}

li {
  display: inline;
}

li a {
  color: black;
  text-decoration: none;
}

.link:hover {
  color: white;
}

.link:before {
  content: "";
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
  background-color: #000;
}

.link:hover:before {
  visibility: visible;
  transform: scaleX(1);
}
<nav>
  <ul>
    <li><a class="link" href="home.html">Home</a></li> -
    <li><a class="link" href="code.html">Code</a></li> -
    <li><a class="link" href="webpages.html">Webpages</a></li> -
    <li><a class="link" href="articles.html">Articles</a></li> -
    <li><a class="link" href="resume.html">Resume</a></li>
  </ul>
</nav>

1 个答案:

答案 0 :(得分:0)

所以你需要添加几行CSS来实现这一目标。到.link:before选择器:

position: absolute;
bottom: 0;
width: 100%;
height: 1px;

它需要宽度和高度属性,以及定位信息。因为下划线的位置是绝对的,我们需要将父元素设置为相对(因此它相对于父元素绝对定位)。因此,我们添加li选择器:

position: relative;

以下是工作代码:

&#13;
&#13;
ul {
  list-style-type: none;
}

li {
  display: inline;
  position: relative;
}

li a {
  color: black;
  text-decoration: none;
}

.link:hover {
  color: white;
}

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

.link:hover:before {
  visibility: visible;
  transform: scaleX(1);
}
&#13;
<nav>
  <ul>
    <li><a class="link" href="home.html">Home</a></li> -
    <li><a class="link" href="code.html">Code</a></li> -
    <li><a class="link" href="webpages.html">Webpages</a></li> -
    <li><a class="link" href="articles.html">Articles</a></li> -
    <li><a class="link" href="resume.html">Resume</a></li>
  </ul>
</nav>
&#13;
&#13;
&#13;