如何修复以下代码..我使用 transform:translateY(-50%)的技术制作 div垂直居中。但是当我将它与动画一起使用时,它首先需要top:50%
然后它翻译给一个混蛋 ..我不希望这个混蛋发生并且元素应该自动进入中心
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>
&#13;
答案 0 :(得分:6)
您的动画规则会使用translateY(-50%)
覆盖scale()
,当动画完成后,之前的规则会再次应用,因此会跳转。
如果您将translateY(-50%)
添加到动画中,它将正常工作。
附注,根据是否在translateY()
之前或之后放置scale()
,其动画效果不同,因为transform
值从右到左应用
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>
答案 1 :(得分:0)
此处的问题是line-height
,但您实际上可以使用calc
来解决此问题。
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>