我在下面有一个圆形的呼吸 click me
按钮,这里我使用 @keyframes
为按钮呼吸设置动画 - 到目前为止一切正常!
但是正如您所见,click me
文本在呼吸动画期间会晃动。
有没有办法避免这种情况的发生?
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
button.circle {
--startSize: 65vh;
--endSize: 85vh;
width: var(--startSize);
height: var(--startSize);
background: teal;
border-radius: 100%;
animation-name: breathe;
animation-play-state: running;
animation-duration: 4.5s;
animation-iteration-count: infinite;
animation-direction: alternate;
border: none;
}
@keyframes breathe {
0% {
width: var(--startSize);
height: var(--startSize);
}
25% {
width: var(--startSize);
height: var(--startSize);
}
75% {
width: var(--endSize);
height: var(--endSize);
}
100% {
width: var(--endSize);
height: var(--endSize);
}
}
<a href="https://www.w3schools.com"><button class="circle centered">Click me</button></a>
最佳答案
也许更好的动画方式是在 ::after
伪元素上使用 transform: scale(...)
。使用这种方法我们可以获得以下好处:
- 动画不再影响文档流1。动画时,prefer
transform
andopacity
over properties likewidth
orheight
.后者会影响它周围的元素(文档流)。变换纯粹是视觉上的——它们在放置方面对其他元素没有影响,这意味着 improved performance . - 文本与动画分开,这意味着不再有抖动。
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
button.circle {
width: 65vh;
height: 65vh;
border: 0;
background-color: transparent;
}
button.circle::after {
z-index: -1;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
content: '';
display: block;
background: teal;
border-radius: 100%;
animation: breathe 4.5s ease infinite alternate running;
}
@keyframes breathe {
from { transform: scale(1); }
to { transform: scale(1.4); }
}
<a href="https://www.w3schools.com"><button class="circle centered">Click me</button></a>
备注:Browser support for this method
1。我意识到该按钮居中并位于 absolute
这意味着它不会影响文档流开始。也就是说,这种使用变换制作动画的方法对于任何一种情况都更加灵活。
关于html - CSS breathing <button> 停止文本晃动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097307/