如何将下划线从中心而不是向左悬停?

时间:2019-03-28 13:22:38

标签: html css

我有一个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 个答案:

答案 0 :(得分:5)

快速解决方案:

将原始位置移动到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>

答案 1 :(得分:4)

您可以使用如下背景简化代码

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>

答案 2 :(得分: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>
= = = 谢谢 = = =