1

I want to make elements that are placed together explode out from each other by increasing the margin on each of them with a CSS animation. The problem I have is that they end up pushing against the top of the container instead of going above the top. Is there any way to just make them expand outwards? You can see what I've done so far in this example. 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>
Rob Kwasowski
  • 2,690
  • 3
  • 13
  • 32

2 Answers2

3

I would use flex to center the boxes vertically, because they would never go out of the parent at the top as long as they are aligned to the top.

$('#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>
TheBlueOne
  • 486
  • 5
  • 13
1

You could also animate the Y location. Although @TheBlueOne has a good solution. Not sure if this might be a better option if scrolling is 100% necessary.

Also, you may need to tweak -100px to whatever you are looking for exactly.

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

https://jsfiddle.net/hLx9w2cz/

Joe Fitzsimmons
  • 1,043
  • 1
  • 8
  • 22