Sass 的三大功能
首先一个提示:Sass 是完全兼容 CSS 的,也就是初学 Sass 还是可以完全用以前纯 CSS 的语法在自己的 xxx.scss 文件中去写的。在 sass.hk 的教程中,列出了 Sass 的七大功能,其实可以逐步按需去学习的,一下子肯定记不住。我这里要演示的,是最重要的三大功能。那种一旦用上就再也离不开的功能啊。
第一个功能:变量使用
先来在一个 meteor 项目中添加 Sass 的支持
meteor create try-sassmeteor add fourseven:scss
meteor 的自动刷新功能很方便,每次修改了代码,页面都会实时刷新。
变量就写成下面这样:
$primary-color: blue;
第二个功能:嵌套
写成这样:
.hero { .action { color: red; &:hover { color: blue; } }}
第三个功能:导入其他 Sass 文件
这个功能可以用来切分项目代码,很实用。
下图来自 sass.hk
注意:实际中一般各个 .scss 文件都要以下划线打头,例如 _hero.scss
。
代码
视频中用到的代码如下,对应的色盘在这里 。
try-sass.html 中这样写:
<head> <title>try-sass</title></head>
<body> <div class="container"> <div class="hero"> <h1>科技拥抱艺术之时</h1> <p>自由牵手理性之日</p> <div class="action">A</div> </div> <div class="main"></div> </div></body>
try-sass.css 中写成这样
body { margin: 0; background-color: #374046;}.container { margin: 30px auto; max-width: 460px; box-shadow: 0 3px 10px rgba(0,0,0,0.23),0 3px 10px rgba(0,0,0,0.16);}.hero { background-color: #607D8B; height: 300px; position: relative;}.hero h1 { color: white; padding-left: 50px; padding-top: 130px; margin-bottom: 11px;}.hero p { color: white; opacity: .8; padding-left: 50px; margin-top: 0;}.hero .action { position: absolute; bottom: -30px; right: 40px; background-color: #FFC107; width: 60px; height: 60px; border-radius: 50%; color: white; font-weight: bold; text-align: center; line-height: 60px; font-size: 1.4em; box-shadow: 0 3px 10px rgba(0,0,0,0.23),0 3px 10px rgba(0,0,0,0.16); transition: all 200ms ease; cursor: pointer;}
.hero .action:hover { transform: scale(1.2) rotate(90deg);}.main { height: 400px; background-color: #fff;}
改写为 scss 语法后,try-sass.scss 如下
@import 'common';@import 'sections/hero';.container { margin: 30px auto; max-width: 460px; box-shadow: 0 3px 10px rgba(0,0,0,0.23),0 3px 10px rgba(0,0,0,0.16);}
.main { height: 300px; background-color: #fff;}
sections/_hero.scss
.hero { background-color: $primary-color; height: 260px; position: relative; h1 { color: white; padding-left: 50px; padding-top: 130px; margin-bottom: 11px; } p { color: white; opacity: .8; padding-left: 50px; margin-top: 0; }}
.hero .action { position: absolute; bottom: -30px; right: 40px; background-color: $accent-color; width: 60px; height: 60px; border-radius: 50%; color: white; font-weight: bold; text-align: center; line-height: 60px; font-size: 1.4em; box-shadow: 0 3px 10px rgba(0,0,0,0.23),0 3px 10px rgba(0,0,0,0.16); transition: all 200ms ease; cursor: pointer; &:hover { transform: scale(1.2) rotate(90deg); }}
_common.scss
$primary-color: #607D8B;$accent-color: #FFC107;
body { margin: 0; background-color: #374046;}