CSS边框底部应在悬停时延伸

时间:2015-03-18 20:04:31

标签: html css

我想创建一个边框动画。如果我将鼠标悬停在链接上,则边框底部应从左侧延伸到右侧。我搜索了很多, 但我不知道如何命名。

这是我的代码:

.a{
    width: 200px;
    display: inline-block;
    transition: 0.5s all;
}

.a:hover{
    border-bottom: 5px solid #037CA9;
}
<a>Benutzername:</a>

我如何设计这个元素,边框底部从左侧延伸到右侧?

5 个答案:

答案 0 :(得分:7)

您可以使用定位的伪元素

&#13;
&#13;
a {
  text-decoration: none;
  position: relative;
}
a::before {
  content: '';
  position: absolute;
  background: red;
  height: 2px;
  top: 100%;
  left: 0;
  width: 0%;
  transition: width 0.5s ease;
}
a:hover::before {
  width: 100%;
}
&#13;
<a href="#">Benutzername:</a>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用缩放到0.001的伪元素,并在悬停时将其缩放回1。这种方法在另一个问题中得到了解释:Expand border from center on hover

要使其从左侧展开,您只需将变换原点更改为0 0

&#13;
&#13;
a{
  display:inline-block;
}
a:after {
  display:block;
  content: '';
  border-bottom: solid 3px #019fb6;
  transform-origin:0 0;
  transform: scaleX(0.001);
  transition: transform 250ms ease-in-out;
}
a:hover:after {
  transform: scaleX(1);
}
&#13;
<a>Benutzername:</a>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我认为你正试图在下面找到这样的小提琴。 我用样式的<a>标记做了一个小例子,并使用了伪<a>元素并给它一个转换,使它在你悬停时扩展。

&#13;
&#13;
a {
    position:relative;
    display:inline-block;
    padding:5px 10px;
    color:#444;
    background:#f3f3f3;
    text-decoration:none;
}
a:after {
    content:'';
    position:absolute;
    background:green;
    display:block;
    height:2px;
    bottom:-2px;
    left:0;
    min-width:0;
    transition:all .2s linear;
    -webkit-transition:all .2s linear;
}

a:hover:after {
    min-width:100%;
}
&#13;
<a href="#">Hover button</a>
&#13;
&#13;
&#13;

可能会添加更多浏览器特定的css转换,以便更兼容多浏览器。有关详细信息,请查看HERE

jsFIDDLE

答案 3 :(得分:0)

如果有人想从中心延伸线,则有解决方法:

a {
  position: relative;
  text-decoration: none;
}
a:after {
  content: '';
  background: #2a57b3;
  display: block;
  height: 2px;
  position: absolute;
  left: 50%;
  bottom: 0;
  width: 0;
  -webkit-transition: all .2s;
  transition: all .2s;
}
a:hover:after {
  width: 100%;
  margin-left: -50%;
}
<a>Hover me!</a>

答案 4 :(得分:-2)

你可以试试这个。

#divname {
position:absolute;
top:0;
height:500px;
}

#divname:hover {
position:absolute;
top:0;
height:600px;
}

这对我有用。

相关问题