CSS菜单悬停下划线动画

时间:2018-12-22 08:00:20

标签: javascript jquery html css

当我将鼠标悬停在菜单项上时(基于此CodePen),我试图创建下划线动画。出于某种原因,我所有的菜单项都带有下划线,而不是悬停时只有一个。我只希望悬停的菜单项带有下划线,而不是所有内容。

这是我的代码:

html {
  background-color: #131313;
}

.pages {
  position: absolute;
  margin: 0;
  padding: 0;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 17px;
  list-style: none;
}

.pages li {
  float: left;
  display: inline-block;
  padding: 15px;
}

.pages a {
  color: white;
  text-decoration: none;
}

.pages a:after {
  content: '';
  position: absolute;
  width: 0;
  height: 3px;
  display: block;
  margin-top: 5px;
  right: 0;
  background: #fff;
  transition: width .4s ease;
}

.pages a:hover:after {
  width: 100%;
  left: 0;
  background: #fff;
}
<ul class="pages">
  <li><a href="#top" id="menu-home">Home</a></li>
  <li><a href="#about" id="menu-about">About</a></li>
  <li><a href="#work" id="menu-work">Work</a></li>
  <li><a href="#projects" id="menu-proj">Projects</a></li>
  <li><a href="#connect" id="menu-connect">Connect</a></li>
</ul>

请帮助!

1 个答案:

答案 0 :(得分:2)

position:absolute中删除.pages a:after。位置为absolute的元素不在常规文档流中。在您的摘要中,您100%的宽度将不是a的100%,而是相对/绝对位置最近的父对象的100%(默认情况下为body;在您的情况下为ul)。

或者,您可以将position:relative设置为li,这样:after元素将成为li的基础。

html {
  background-color: #131313;
}

.pages {
  position: absolute;
  margin: 0;
  padding: 0;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 17px;
  list-style: none;
}

.pages li {
  float: left;
  display: inline-block;
  padding: 15px;
  position: relative
}

.pages a {
  color: white;
  text-decoration: none;
}

.pages a:after {
  content: '';
  position: absolute;
  width: 0;
  height: 3px;
  display: block;
  margin-top: 5px;
  right: 0;
  background: #fff;
  transition: width .4s ease;
}

.pages a:hover:after {
  width: 100%;
  left: 0;
  background: #fff;
}
<ul class="pages">
  <li><a href="#top" id="menu-home">Home</a></li>
  <li><a href="#about" id="menu-about">About</a></li>
  <li><a href="#work" id="menu-work">Work</a></li>
  <li><a href="#projects" id="menu-proj">Projects</a></li>
  <li><a href="#connect" id="menu-connect">Connect</a></li>
</ul>

我的解释可能很复杂,因此您可以查看下面的代码段。我试图解释定位。

.box {
  width: 100px;
  height: 100px;
}

#parent {
  background: pink;
  width: 200px;
  height: 200px;
}

#child1 {
  position: relative;
  top: 10px;
  left: 10px;
  background: lightgreen;
}

#child2 {
  position: absolute;
  background: lightyellow;
}
<div id="parent" class='box'>
  <!--parent-->

  <!-- relative element stays relative to it's original position but can be shifted-->
  <div id="child1" class='box'>position:relative with "top"and"left" of 10px</div>

  <div id="child2" class='box'>position:absolute</div>
</div>
<!--
notice how yellow box is stays where it should be without "top"&"left" assigned, but it's owerlaping shifted green box
-->