将相同的样式组合成一个 class 并使用它或相反的方式,哪个更有效?

Which one is more efficient combining same styles into one class and using it or the other way around?

以下哪一个代码片段的性能更好?

第一个案例

.a {
 color: #000;
 width: 20px;
 -webkit-transition: 0.3s all;
 -moz-transition: 0.3s all;
 -o-transition: 0.3s all;
 transition: 0.3s all;
}
.b {
 color: #333;
 width: 40px;
 -webkit-transition: 0.3s all;
 -moz-transition: 0.3s all;
 -o-transition: 0.3s all;
 transition: 0.3s all;
}
.c {
 color: #999;
 width: 90px;
 -webkit-transition: 0.3s all;
 -moz-transition: 0.3s all;
 -o-transition: 0.3s all;
 transition: 0.3s all;
}
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>

第二种情况

.a {
 color: #000;
 width: 20px;
}
.b {
 color: #333;
 width: 40px;
}
.c {
 color: #999;
 width: 90px;
}
.smooth {
 -webkit-transition: 0.3s all;
 -moz-transition: 0.3s all;
 -o-transition: 0.3s all;
 transition: 0.3s all;
}
<div class="a smooth"></div>
<div class="b smooth"></div>
<div class="c smooth"></div>

在第一种情况下,在 div 中使用相同的样式,而在其他情况下,相同的样式被组合到一个 class 中,并且 class 被添加到 div 中s.

哪个表现更好?

在性能方面差异不大,但是建议练习所谓的 DRY CSS。

如果我没记错的话,DRY CSS 是 a term coined by Jeremy Clarke 大约 4 年前。 DRY 表示 "Don't Repeat Yourself",因此 你的第二个解决方案应该是首选

Harry Roberts (csswizardry.com) explained 使用 DRY 的两个最重要的原因 CSS:

  • Less actual code, meaning smaller file sizes, less for the user to have to download, more efficient code, etc.
  • Less to have to maintain; not repeating yourself means that you can make fewer changes to your codebase.