将CSS从中心增长到固定宽度

时间:2017-03-20 17:26:25

标签: html css css3 animation

我有以下悬停效果,效果很好。但是,我正在尝试添加固定宽度的蓝线。例如,最大宽度为100px。当我尝试修改下面的代码时,动画会中断并且不会从中心增长。

有关如何修复下面代码的任何想法,以便从中心动画到固定宽度?

body {
  width:100%;
}

div {
  display:block;
  position:absolute;
  top:45%;
  left:50%;
  border-bottom:4px solid blue;
  width:0%;
  text-align:center;
  animation: line 2s linear forwards;
}

@keyframes line {
  from {
    left:50%;
    width:0%;
  }
  to {
    left:5%;
    width:90%;
  }
}
<div>Heading</div>

2 个答案:

答案 0 :(得分:1)

我会使用:after pseudo-element而不是将边框添加到实际元素中。我也缩短了你的动画时间,因为它似乎有点长:

body {
  width:100%;
}

div {
  display:inline-block;
  position:absolute;
  top:45%;
  left:50%;
  text-align:center;
}
  div:hover:after {
    content:"";
    display:block;
    width:0;
    margin:0 auto;
    height:4px;
    background:blue;
    animation:line .5s linear forwards;
  }

@keyframes line {
  from {
    width:0%;
  }
  to {
    width:100%;
  }
}
<div>Heading</div>

您也可以在没有keyframes的情况下执行此操作:

body {
  width:100%;
}

div {
  display:inline-block;
  position:absolute;
  top:45%;
  left:50%;
  text-align:center;
}
  div:after {
    content:"";
    display:block;
    height:4px;
    background:blue;
    width:0;
    margin:0 auto;
    transition:.5s all;
  }
  div:hover:after {
    width:100%;
  }
<div>Heading</div>

答案 1 :(得分:1)

解决方案1 ​​

只需添加一个可以限制宽度的其他span元素:

&#13;
&#13;
body {
  width: 100%;
}

div {
  display: block;
  position: absolute;
  top: 45%;
  left: 50%;
  width: 0%;
  animation: line 2s linear forwards;
}

.heading {
  display: block;
  text-align: center;
  max-width: 200px;
  border-bottom: 4px solid blue;
  margin: 0px auto;
}

@keyframes line {
  from {
    left: 50%;
    width: 0%;
  }
  to {
    left: 5%;
    width: 90%;
  }
}
&#13;
<div><span class="heading">Heading</span></div>
&#13;
&#13;
&#13;

解决方案2

不要使用绝对定位来集中div

&#13;
&#13;
div {
  display: block;
  width: 0%;
  animation: line 2s linear forwards;
  text-align: center;
  max-width: 200px;
  border-bottom: 4px solid blue;
  margin: 0px auto;
}

@keyframes line {
  from {
    width: 0%;
  }
  to {
    width: 90%;
  }
}
&#13;
<div>Heading</div>
&#13;
&#13;
&#13;