CSS动画:元素位于容器顶部上方且边距增加

时间:2019-05-01 20:37:51

标签: css

我想通过CSS动画通过增加每个元素的边距来使放置在一起的元素相互爆炸。我的问题是,它们最终会推向容器的顶部,而不是越过顶部。有什么方法可以使它们向外扩展? 您可以在此示例中看到我到目前为止所做的。 https://jsfiddle.net/liquidmetalrob/kozbpct1/2/

$('#start').click(function() {
  $('.abc').addClass('move')
})
#page {
  height: 200px;
  width: 200px;
  background: lightgrey;
}

.abc {
  color: red;
  padding: 10px;
  background: black;
  width: 30px;
}

.move {
  animation: move 0.6s cubic-bezier(1, 0, 1, 1);
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

@keyframes move {
  from {
    margin: 0px;
  }
  to {
    margin: 50px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body>
  <div id=page>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
  </div>
  <button id=start>
          Start
        </button>
</body>

</html>

2 个答案:

答案 0 :(得分:3)

我将使用flex将框垂直居中,因为只要框对齐顶部,它们就永远不会超出其父级。

$('#start').click(function() {
  $('.abc').addClass('move')
})
#page {
  height: 200px;
  width: 200px;
  background: lightgrey;
  /*new code*/
  display: flex;
  flex-flow: column;
  justify-content: center;
  /*new code end*/
}

.abc {
  color: red;
  padding: 10px;
  background: black;
  width: 30px;
}

.move {
  animation: move 0.6s cubic-bezier(1, 0, 1, 1);
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

@keyframes move {
  from {
    margin: 0px;
  }
  to {
    margin: 50px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body>
  <div id=page>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
    <div class=abc>
      ABC
    </div>
  </div>
  <button id=start>
          Start
        </button>
</body>

</html>

答案 1 :(得分:1)

您还可以为Y位置设置动画。虽然@TheBlueOne有一个很好的解决方案。如果滚动是100%必需的,则不确定这是否是更好的选择。

此外,您可能需要将-100px调整为您要确切查找的内容。

@keyframes move {
  from { margin: 0px; 
  transform: translateY(0px);}
  to { margin: 50px; 
  transform: translateY(-100px);}
}

https://jsfiddle.net/hLx9w2cz/

相关问题