The engine evaluates each rule from right to left,starting from the rightmost selector (called the “key”) and moving through each selector until it finds a match or discards the rule. (The “selector” is the document element to which the rule should apply.)
例如:
- ul li a {...}
- #footer h3 {...}
- * html #atticPromo ul li a {...]
- #content #blog {
- /* ... */
- }
- /* line 85,../sass/screen.scss */
- #content #flickr {
- /* ... */
- }
- #content #flickr div p {
- /* ... */
- }
这似乎有点尴尬..我做错了什么?这是我和Sass之间的沟通问题吗?我们失去了吗?
编辑:
一些SCSS代码:
- #flickr {
- @include columns(5,8);
- background: url('../img/ipadbg.png') no-repeat;
- #ipod-gloss {
- z-index: 999;
- position: relative;
- }
- div {
- margin-top: -80px;
- margin-right: 20px;
- h2 {
- color: $white;
- font-size: 24px;
- }
- p {
- margin-top: 40px;
- }
- }
- }
Side Bonus!:文章说浏览器(或至少Firefox)从右到左搜索选择器.我不明白为什么这是一个更有效率的原因.任何线索?
解决方法
经验法则说您应该尝试限制自己进行三级嵌套,如果没有必要,您应该避免嵌套ID.
但是,我认为嵌套太多并不是最大的问题.一旦我意识到mixins的力量,我就用了很多.
例如,这是我经常使用的按钮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
你看,相当多的代码.将这样的混合应用到页面上的许多元素将导致大的CSS文件需要更长的时间来解释.
在老式的CSS方式中,您可以给每个按钮元素类.小按钮.但是这种方法会使用非语义类来污染你的标记.
Sass提供了一个解决方案:选择器通过@extend directive继承.
如果您为mixin的参数设置默认值,您还可以提供一个简单的类,它使用默认的mixins:
- // 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代码.