html - CSS breathing <button> 停止文本晃动

标签 html css

我在下面有一个圆形的呼吸 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. 动画不再影响文档流1。动画时,prefer transform and opacity over properties like width or height .后者会影响它周围的元素(文档流)。变换纯粹是视觉上的——它们在放置方面对其他元素没有影响,这意味着 improved performance .
  2. 文本与动画分开,这意味着不再有抖动。

.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/

相关文章:

jquery - 调整 bootstrap-select 组件大小的问题

javascript - 如何通过ID javascript获取元素子跨度的innerhtml

javascript - 设置显示:none if element contains no text

javascript - “节点”未定义。我们如何在应用程序级别定义?

javascript - 离线缓存 - html5

css - 如何在 CSS 中的图像中添加渐变/滤镜

javascript - 在需要填充一个文本字段后并同时填充另一个文本字段时动态执行函数

css - 自举网格列之间的长间隙

javascript - 为什么图像显示空间并向右走,应该是填补空白

css - 使用 withStyles api 时,如何允许通过 props 自定义 React 组件的样式?