从中心开始 CSS 下划线动画而非从左侧开始

5

我有一个带有给定悬停效果的 ul,使用 :after 实现。这很好用,但我想让它从中间开始而不是左边。

我的代码:

ul.my-list{ margin: 20px; padding: 0px; width: 200px;}
ul.my-list li{ list-style: none; position: relative; display: inline;}
ul.my-list li a{ color:#333; text-decoration: none;}
ul.my-list li:after{ content: ''; position: absolute; left: 0px; bottom: -2px; width:0px; height: 2px; background: #333; transition: all 0.45s;}
ul.my-list li:hover:after{ width: 100%;}
ul.my-list li a:hover{ text-decoration: none;}
<ul class="my-list">
  <li><a href="#">Welcome to my website</a></li>
</ul>

3个回答

9
快速解决方案:
将原始位置移动到left:50%,然后在悬停时将其移动到left:0

ul.my-list {
  margin: 20px;
  padding: 0px;
  width: 200px;
}

ul.my-list li {
  list-style: none;
  position: relative;
  display: inline;
}

ul.my-list li a {
  color: #333;
  text-decoration: none;
}

ul.my-list li:after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: -2px;
  width: 0px;
  height: 2px;
  background: #333;
  transition: all 0.45s;
}

ul.my-list li:hover:after {
  width: 100%;
  left: 0;
}

ul.my-list li a:hover {
  text-decoration: none;
}
<ul class="my-list">
  <li><a href="#">Welcome to my website</a></li>
</ul>


6
您可以使用以下类似的背景来简化您的代码。

ul.my-list {
  margin: 20px;
  padding: 0px;
  width: 200px;
}

ul.my-list li {
  list-style: none;
  display: inline-block;
  padding-bottom:2px; /*the space for the gradient*/
  background: linear-gradient(#333,#333) center bottom; /*OR bottom right OR bottom left*/
  background-size: 0% 2px; /*width:0% height:2px*/
  background-repeat:no-repeat; /* Don't repeat !!*/
  transition: all 0.45s;
}

ul.my-list li a {
  color: #333;
  text-decoration: none;
}


ul.my-list li:hover {
  background-size: 100% 2px; /*width:100% height:2px*/
}
<ul class="my-list">
  <li><a href="#">Welcome to my website</a></li>
</ul>


1

这很简单,你调用元素后左50%,这意味着当你悬停在宽度为100%和左0的元素上时,它已经向中间添加了一些过渡效果,因此看起来像是从中间到左右。这是代码:

ul.my-list{ margin: 20px; padding: 0px; width: 200px;}
ul.my-list li{ list-style: none; position: relative; display: inline;}
ul.my-list li a{ color:#333; text-decoration: none;}
ul.my-list li:after{ 
  content: ''; 
  position: absolute; 
  left: 50%; /* change this code 0 to 50%*/
  bottom: -2px; 
  width:0px; 
  height: 2px; 
  background: #333; 
  transition: all 0.45s;
}
ul.my-list.rtl li:after { right: 0; left: inherit; }
ul.my-list li:hover:after{ left:0; width: 100%;} /* add poperty left 0 */
ul.my-list li a:hover{ text-decoration: none;}
<ul class="my-list">
  <li><a href="#">Welcome to my website</a></li>
</ul>
<h2>left start and end right</h2>
<ul class="my-list rtl">
  <li><a href="#">Welcome to my website</a></li>
</ul>

= = = Thank you = = =


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接