首页 > 解决方案 > CSS - 带有边框半径的动画比例

问题描述

我正在制作一个带有缩放框的动画,它以 8 像素四舍五入。参考:https ://codepen.io/anon/pen/ePGxqy 。然而,当盒子展开时,圆角很奇怪,我不想通过改变它在关键帧中的宽度来缩放它。如何正确缩放带有圆形边框的圆形框?

#box {
  position: relative;
  width: 55px;
  height: 55px;
  background: #aaa;
  margin: 0 auto;
  border-radius: 8px;
  animation-name: singleRevert;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

#box:hover {
  animation-name: singleExpend;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

@keyframes singleRevert {
  0% {
    transform: scaleX(7.5) scaleY(0.46)
  }
  50% {
    transform: scaleX(1) scaleY(0.46)
  }
  100% {
    transform: scaleX(1) scaleY(1)
  }
}

@keyframes singleExpend {
  0% {
    transform: scaleX(1) scaleY(1)
  }
  50% {
    transform: scaleX(1) scaleY(0.46)
  }
  100% {
    transform: scaleX(7.5) scaleY(0.46)
  }
}
<div id="box"></div>

标签: cssanimationtransform

解决方案


基本上,您需要为边框半径设置动画以匹配框的比例。

为简单起见,如果您的框半径为 8 像素,并且您将框缩放 8 倍,那么您的边框半径在缩放后的大小应该为 1 像素。如果您的框缩放为 0.5,则边框将为 16px;

或者,您可以为框的宽度和高度设置动画。这将尊重边界,在这种情况下您不必更改它们。

更新了您的版本:

#box {
  position: relative;
  width: 55px;
  height: 55px;
  background: #aaa;
  margin: 0 auto;
  border-radius: 8px;
  animation-name: singleRevert;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

#box:hover {
  animation-name: singleExpend;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

@keyframes singleRevert {
  0% {
    transform: scaleX(8) scaleY(0.5);
    border-radius: 1px;
  }
  50% {
    transform: scaleX(1) scaleY(0.5)
    border-radius: 8px;
  }
  100% {
    transform: scaleX(1) scaleY(1)
    border-radius: 8px;
  }
}

@keyframes singleExpend {
  0% {
    transform: scaleX(1) scaleY(1)
    border-radius: 8px;
  }
  50% {
    transform: scaleX(1) scaleY(0.5)
    border-radius: 8px;
  }
  100% {
    transform: scaleX(8) scaleY(0.5)
    border-radius: 1px;
  }
}
<div id="box"></div>

简单版:

#box {
  position: relative;
  width: 55px;
  height: 55px;
  background: #aaa;
  margin: 0 auto;
  border-radius: 8px;
  animation-name: singleRevert;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

#box:hover {
  animation-name: singleExpend;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

@keyframes singleRevert {
  0% {
    width: 400px;
    height: 40px;
  }
  50% {
    width: 55px;
    height: 40px;
  }
  100% {
    width: 55px;
    height: 55px;
  }
}
@keyframes singleExpend {
  0% {
    width: 55px;
    height: 55px;
  }
  50% {
    width: 55px;
    height: 40px;
  }
  100% {
    width: 400px;
    height: 40px;
  }
}
<div id="box"></div>


推荐阅读