您必须在可维护性(嵌套可以更轻松地在样式表中找到方法)和渲染性能之间找到折衷方案。
根据经验,您应该尝试将自己限制在三层嵌套,并且如果没有必要,您应该避免嵌套 ID。
不过,我认为嵌套太多并不是最大的问题。当我意识到 mixin 的强大功能后,我就大量使用它们。
例如,这是我经常使用的按钮 mixin:
@mixin small-button($active-color: $active-color, $hover-color: $button-hover-color, $shadow: true)
display: inline-block
padding: 4px 10px
margin:
right: 10px
bottom: 10px
border: none
background-color: $button-color
color: $font-color-inv
+sans-serif-font(9px, 700)
text-align: center
text-transform: uppercase
cursor: pointer
@if $shadow
+light-shadow
&:hover
text-decoration: none
background-color: $hover-color
&:last-child
margin-right: 0
a
color: $font-color-inv
&, &:hover
text-decoration: none
&.disabled
+opacity(0.75)
&:hover
background-color: $button-color
&.active
background-color: $active-color
&.disabled:hover
background-color: $active-color
你看,相当多的代码。将此类 mixin 应用于页面上的许多元素将导致生成一个大的 CSS 文件,并且需要更长的时间来解释。
在老式的 CSS 方式中,你可以给每个按钮元素,例如.small-button 类。但这种方法会用无语义的类污染您的标记。
Sass 提供了一个解决方案:通过选择器继承@extend指令 http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#extend.
如果您为 mixin 的参数设置默认值,您还可以提供一个简单的类,它将 mixin 与您的默认值一起使用:
// Use this mixin via @extend if you are fine with the parameter defaults
.small-button
+small-button
然后你可以在各种上下文中继承这个类:
#admin-interface
input[type=submit]
@extend .small-button
生成的 CSS 语句将 .small 按钮的所有用法聚合到一条规则中,并使用逗号分隔的选择器:
.small-button, #admin-interface input[type=submit] {
display: inline-block;
...
}
总之,简单地使用 Sass 会影响 CSS 性能。然而,如果使用得当,由于结构良好和 DRY 代码,它是可维护的,它可以正确分离标记和样式(仅语义类),并允许智能和高性能的 CSS 代码。