Align vertically with translateY (-50%), giving a jerk?

How can I fix the code below. I used the transform: translateY (-50%) technique to make the div vertically center . But when I use it with animation, it first takes top:50% , then it translates the giving jerk . I don't want a jerk to happen, and the element should automatically go to the center.

 body, html { height: 100%; background: #c9edff; text-align: center; } .element { position: relative; top: 50%; transform: translateY(-50%); font-family: arial; font-size: 20px; line-height: 1.8em; -webkit-animation-name: zoom; -webkit-animation-duration: 0.6s; animation-name: zoom; animation-duration: 0.6s; } @-webkit-keyframes zoom { from { -webkit-transform: scale(0); } to { -webkit-transform: scale(1) } } @keyframes zoom { from { transform: scale(0) } to { transform: scale(1) } } 
 <div class="element"> Vertical Align is Awesome! <br /> But with animation its giving a jerk!<br/> Please Fix </div> 
+5
source share
2 answers

Your animation rule overwrites translateY(-50%) with scale() , and when the animation is complete, the previous rule is applied again, so it skips.

If you add translateY(-50%) to the animation, it will work fine.

A side note based on the fact that it puts translateY() before or after scale() , it animates differently, as transform values ​​are applied from right to left

 body, html { height: 100%; background: #c9edff; text-align: center; } .element { position: relative; top: 50%; transform: translateY(-50%); font-family: arial; font-size: 20px; line-height: 1.8em; -webkit-animation-name: zoom; -webkit-animation-duration: 0.6s; animation-name: zoom; animation-duration: 0.6s; } @-webkit-keyframes zoom { from { -webkit-transform: translateY(-50%) scale(0); } to { -webkit-transform: translateY(-50%) scale(1); } } @keyframes zoom { from { transform: translateY(-50%) scale(0); } to { transform: translateY(-50%) scale(1); } } 
 <div class="element"> Vertical Align is Awesome! <br /> But with animation its giving a jerk!<br/> Please Fix </div> 
+6
source

The problem here is line-height , but you can really use calc to fix this.

transform: translateY(calc(- 50% + 1.8em));

 body, html { height: 100%; background: #c9edff; text-align: center; } .element { position: relative; top: 50%; transform: translateY(calc(- 50% + 1.8em)); font-family: arial; font-size: 20px; line-height: 1.8em; -webkit-animation-name: zoom; -webkit-animation-duration: 0.6s; animation-name: zoom; animation-duration: 0.6s; } @-webkit-keyframes zoom { from { -webkit-transform: scale(0); } to { -webkit-transform: scale(1) } } @keyframes zoom { from { transform: scale(0) } to { transform: scale(1) } } 
 <div class="element"> Vertical Align is Awesome! <br /> But with animation its giving a jerk!<br/> Please Fix </div> 
0
source

Source: https://habr.com/ru/post/1267262/


All Articles