2013-04-12 44 views
2

当使用transformkeyframes结合使用时,我试图实现DRY CSS代码。比方说,我有以下几点:如何在使用变换和关键帧时创建干燥CSS

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); 
    } 
} 

JSFiddle example

如何防止在动画中执行scale(0.8)translateY(100px)?我只希望它来回旋转,而不必在每个步骤的变换内应用这些属性。在这里,只使用两个步骤(fromto),但是如果使用多个步骤(例如用0%20%40%60%80%100%),这将意味着有大量重复的代码。正如你可以想象的那样,当稍后出现更改时,这不是很好。

最终,我正在寻找这样的事情(这是不可能的,因为transform属性将得到重写):

#box { 
    transform: scale(0.8) translateY(100px); 
} 

@keyframes animate { 
    from { 
     transform: rotate(10deg); 
    } 
    to { 
     transform: rotate(-10deg); 
    } 
} 

这甚至可能吗?

Ps。我不在寻找答案,您可以将width/height更改为scale和/或将margin/top属性更改为translate。 LESS/SASS也没有使值容易改变,因为它仍然会导致重复的代码。

回答

3

我放在一起两种选择你 - jsFiddle

选项1 - 不干燥而多了几分凝结:

#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 - 从技术上讲干的,但不一定是“好“

<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 ma如果你使用的是更加复杂的动画,但是我不确定是否只是将它包装在包含div中,并且缩放/翻译包含div将在小范围内提供任何真正的好处。

+0

尽管我对解决方案并不满意,但现在我明白了解决方案是不可能的。然而,你的第二个选择对我来说更好,因为不需要复制粘贴。非常感谢! – MarcoK

+1

@MarcoK谢谢,说实话,这是我第一次看到DRY的概念。我可能会在我的网站上使用它来进行一些重复的重复样式。 – apaul

0

哇,所以我认为肯定有办法做到这一点,而不必为每个关键帧动画重写scale和translateY属性。我尝试了几种不同的东西,但是我无法得到你想要的结果。几乎看起来,如果参数是新的,转换应该能够接受更多参数而不覆盖旧参数。

我知道你说你不想使用LESS/SASS,因为它在技术上不是DRY,但是如果你想在一个地方编码,并且在任何地方都要更新,我会推荐。我会认为它干,因为你不重复自己(即使代码是)。我想不出有什么其他的办法来得到你想要的。

+0

首先,感谢您的努力。听到你实际上碰到了和我一样的结论很遗憾,但我仍然希望有更好的方法来做到这一点。 – MarcoK