CSS从中心过渡

时间:2018-03-11 19:52:36

标签: javascript html css css-transitions css-animations

我有一些水平线,使用div元素制作。所有这些都通过使用CSS,设置转换和JS来设置新的width动画。这是我目前的代码和结果:

HTML:

<div style="bottom: 10%;" class="lines-horizontal"></div>
<div style="bottom: 20%;" class="lines-horizontal"></div>
<div style="bottom: 30%;" class="lines-horizontal"></div>
<div style="bottom: 40%;" class="lines-horizontal"></div>
<div style="bottom: 50%;" class="lines-horizontal"></div>
<div style="bottom: 60%;" class="lines-horizontal"></div>
<div style="bottom: 70%;" class="lines-horizontal"></div>
<div style="bottom: 80%;" class="lines-horizontal"></div>
<div style="bottom: 90%;" class="lines-horizontal"></div>
<div style="bottom: 100%;" class="lines-horizontal"></div>

CSS:

.lines-horizontal {
  position: relative;
  width: 0%;
  transition: width 2s;
  height: 5px;
  background-color: black;
  opacity: 0.2;
  z-index: -5;
  margin-bottom: 10px;
}

JS:

var horizontalLines = document.getElementsByClassName("lines-horizontal")
for (var hLines = 0; hLines < horizontalLines.length; hLines++) {
  horizontalLines[hLines].style.width = "100%"
}

结果:https://jsfiddle.net/u5Lfu11j/4/

这里的问题是线条从左边开始动画。就像有一个transform-origin属性一样,除了转换/动画之外,我有什么方法可以做同样的事情吗?我希望能够将线条设置为从中心开始并向外扩展。

2 个答案:

答案 0 :(得分:1)

margin: auto将为您提供从中心所需的转换:

.lines-horizontal {
  position: relative;
  width: 0%;
  transition: width 2s;
  height: 5px;
  background-color: black;
  opacity: 0.2;
  z-index: -5;
  margin: 0px auto 10px auto;
}

https://jsfiddle.net/u5Lfu11j/22/

答案 1 :(得分:0)

如果只使用一个元素和渐变背景,那么更简单的解决方案然后为背景大小设置动画不使用JS

.box {
  height:200px;
  background-image:linear-gradient(rgba(0,0,0,0.2) 30%,transparent 30%);
  background-size:0% 20px;
  background-position:50% 0;
  background-repeat:repeat-y;
  animation:anim 2s forwards;
}
@keyframes anim {
  from{
    background-size:0% 20px;
  }
  to {
    background-size:100% 20px;
  }

}
<div class="box">

</div>

如果您想要以不同方式为它们设置动画,您也可以将它们视为不同的元素:

.line {
  height: 15px;
  margin-bottom: 15px;
  background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2));
  background-size: 0% 100%;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

.line:nth-child(1) {
  animation: anim 2s forwards;
}
.line:nth-child(2) {
  animation: anim 2s forwards 0.5s;
}
.line:nth-child(3) {
  animation: anim 2s forwards 1s;
}

@keyframes anim {
  from {
    background-size: 0% 100%;
  }
  to {
    background-size: 100% 100%;
  }
}
<div>
  <div class="line">
  </div>
  <div class="line">
  </div>
  <div class="line">
  </div>
</div>