我正在努力实现 DRY使用 transform
时的 CSS 代码结合 keyframes
.假设我有以下内容:
HTML
<div id="box"></div>
CSS
#box {
width:300px;
height:300px;
background-color:red;
animation: animate 5s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-in-out;
}
@keyframes animate {
from {
transform: scale(0.8) translateY(100px) rotate(10deg);
}
to {
transform: scale(0.8) translateY(100px) rotate(-10deg);
}
}
我怎样才能避免执行 scale(0.8)
和 translateY(100px)
动画里面?我只希望它来回旋转,而不必在每一步的转换中应用这些属性。此处仅使用两个步骤(from
和 to
),但如果使用多个步骤(例如 0%
、20%
、40%
、60%
、80%
、100%
) 这将意味着很多重复的代码。正如您可以想象的那样,当更改稍后出现时,这不是很好。
最终,我正在寻找这样的东西(这是不可能的,因为 transform
属性将被覆盖):
#box {
transform: scale(0.8) translateY(100px);
}
@keyframes animate {
from {
transform: rotate(10deg);
}
to {
transform: rotate(-10deg);
}
}
这可能吗?
附言。我不是在寻找您可以更改 width
的答案/height
至 scale
和/或更改 margin
/top
属性(property)translate
. LESS/SASS 也无法使值易于更改,因为它仍然会导致重复代码。
最佳答案
我为您整理了两个选项- jsFiddle
选项 1- 不是 DRY,而是更简洁:
#box {
width:300px;
height:300px;
background:red;
animation: animate 1s ease-in-out 0s infinite alternate;
}
@keyframes animate {
from {
transform: scale(0.8) translateY(100px) rotate(10deg);
}
to {
transform: scale(0.8) translateY(100px) rotate(-10deg);
}
}
选项 2- 技术上 DRY,但不一定“更好”
<div id="option2">
<div id="box2"></div>
</div>
#option2{
transform: scale(0.8) translateY(100px);
}
#box2 {
width:300px;
height:300px;
background-color:blue;
animation: animate2 6s ease-in-out 0s infinite alternate;
}
@keyframes animate2 {
0%, 40%, 80% {
transform: rotate(10deg);
}
20%, 60%, 100% {
transform: rotate(-10deg);
}
}
如果您使用的是更复杂的动画,我猜想使用选项 2 可能是值得的,但我不确定是否只是将它包装在包含 div
中并缩放/翻译包含的 div
会在小规模上提供任何真正的好处。
关于css - 如何在使用变换和关键帧时创建 DRY CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15971271/