Sass用法及常用方法整理

父选择器 & (Referencing Parent Selectors: &)

a {
  font-weight: bold;
  text-decoration: none;
  &:hover { text-decoration: underline; }
  body.firefox & { font-weight: normal; }
}
编译为

a {
  font-weight: bold;
  text-decoration: none; }
  a:hover {
    text-decoration: underline; }
  body.firefox a {
    font-weight: normal; }

& 必须作为选择器的第一个字符,其后可以跟随后缀生成复合的选择器,例如

#main {
  color: black;
  &-sidebar { border: 1px solid; }
}
编译为

#main {
  color: black; }
  #main-sidebar {
    border: 1px solid; }

属性嵌套 (Nested Properties)

.funky {
  font: {
    family: fantasy;
    size: 30em;
    weight: bold;
  }
}
编译为

.funky {
  font-family: fantasy;
  font-size: 30em;
  font-weight: bold; }

变量 $ (Variables: $)

SassScript 最普遍的用法就是变量,变量以美元符号开头,赋值方法与 CSS 属性的写法一样:

$width: 5em;

直接使用即调用变量:

#main {
  width: $width;
}

 

Mixins(混入)

混入(mixin)允许您定义可以在整个样式表中重复使用的样式,从而避免了使用无语意的类(class),比如 .float-left。混入(mixin)还可以包含所有的CSS规则,以及任何其他在Sass文档中被允许使用的东西。他们甚至可以带参数,引入变量,只需少量的混入(mixin)代码就能输出多样化的样式。

定义的混入@mixin 使用 @include 引用。

简单的例子:

//定义一个mixin
@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}

//引用mixin
.page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

转译后:

.page-title {
  font-family: Arial;
  font-size: 20px;
  font-weight: bold;
  color: #ff0000;
  padding: 4px;
  margin-top: 10px; 
}

插值语句 #{} (Interpolation: #{})

通过 #{} 插值语句可以在选择器或属性名中使用变量:

$name: foo;
$attr: border;
p.#{$name} {
  #{$attr}-color: blue;
}
编译为

p.foo {
  border-color: blue; }

@extend

在设计网页的时候常常遇到这种情况:一个元素使用的样式与另一个元素完全相同,但又添加了额外的样式。通常会在 HTML 中给元素定义两个 class,一个通用样式,一个特殊样式。假设现在要设计一个普通错误样式与一个严重错误样式,一般会这样写:

<div class="error seriousError">
  Oh no! You've been hacked!
</div>
样式如下

.error {
  border: 1px #f00;
  background-color: #fdd;
}
.seriousError {
  border-width: 3px;
}
麻烦的是,这样做必须时刻记住使用 .seriousError 时需要参考 .error 的样式,带来了很多不变:智能比如加重维护负担,导致 bug,或者给 HTML 添加无语意的样式。使用 @extend 可以避免上述情况,告诉 Sass 将一个选择器下的所有样式继承给另一个选择器。

.error {
  border: 1px #f00;
  background-color: #fdd;
}
.seriousError {
  @extend .error;
  border-width: 3px;
}
上面代码的意思是将 .error 下的所有样式继承给 .seriousError,border-width: 3px; 是单独给 .seriousError 设定特殊样式,这样,使用 .seriousError 的地方可以不再使用 .error。

其他使用到 .error 的样式也会同样继承给 .seriousError,例如,另一个样式 .error.intrusion 使用了 hacked.png 做背景,<div class="seriousError intrusion"> 也同样会使用 hacked.png 背景。

.error.intrusion {
  background-image: url("/image/hacked.png");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值