变量是Sass中最简单的特性之一,但有时候也会使用不当。建立站点范围内有语义化的变量,是不可或缺的工做。若是命名很差,他会变得难以理解和重复使用。css
这里有一些命名变量的小技巧,提供参考:html
这有一个好的示例:web
$orange: #ffa600; $grey: #f3f3f3; $blue: #82d2e5; $link-primary: $orange; $link-secondary: $blue; $link-tertiary: $grey; $radius-button: 5px; $radius-tab: 5px;
这个是很差的示例:sass
$link: #ffa600; $listStyle: none; $radius: 5px;
Mixins是实现代码块的一种伟大方式,能够在一个站点内屡次使用。然而,@include
定义好的Mixins和在CSS代码中复制、粘贴没什么不同。它将会让你的CSS代码生成不少重复的代码,让你的文件变得愈来愈臃肿。url
到目前为止,Mixins只适合那种须要经过传递参数来快速建立样式的情形。spa
例如:code
@mixin rounded-corner($arc) { -moz-border-radius: $arc; -webkit-border-radius: $arc; border-radius: $arc; }
rounded-corner
这个Mixins能够在任何状况下使用,仅仅经过改变其参数$arc
的值,将获得不一样的代码:htm
.tab-button { @include rounded-corner(5px); } .cta-button { @include rounded-corner(8px); }
像这样使用Mixins是不明智的:blog
@mixin cta-button { padding: 10px; color: #fff; background-color: red; font-size: 14px; width: 150px; margin: 5px 0; text-align: center; display: block; }
这个Mixins没有传递任何参数,更建议使用%placeholder
来建立,这也是接下来要说的下一点。get
与Mixins不一样,%placeholder也能够屡次使用,并且不会生成重复的代码。这使得输入的CSS更友好,更干净。
%bg-image { width: 100%; background-position: center center; background-size: cover; background-repeat: no-repeat; } .image-one { @extend %bg-image; background-image:url(/img/image-one.jpg"); } .image-two { @extend %bg-image; background-image:url(/img/image-two.jpg"); }
编译出来的CSS:
.image-one, .image-two { width: 100%; background-position: center center; background-size: cover; background-repeat: no-repeat; } .image-one { background-image:url(/img/image-one.jpg") ; } .image-two { background-image:url(/img/image-two.jpg") ; }
多个选择器运用了相同的%placeholder
也只会输出一次代码。没有引用的%placeholder
是不会输出任何CSS代码。
和以前的Mixins配合在一块儿使用,既可保持Mixins灵活性,并且还能够保持代码的简洁与干净。
/* PLACEHOLDER ============================================= */ %btn { padding: 10px; color:#fff; curser: pointer; border: none; shadow: none; font-size: 14px; width: 150px; margin: 5px 0; text-align: center; display: block; } /* BUTTON MIXIN ============================================= */ @mixin btn-background($btn-background) { @extend %btn; background-color: $btn-background; &:hover { background-color: lighten($btn-background,10%); } } /* BUTTONS ============================================= */ .cta-btn { @include btn-background(green); } .main-btn { @include btn-background(orange); } .info-btn { @include btn-background(blue); }