sass入门(三)

二. 混合器
当样式变得越来越复杂,需要大段大段的重用样式的代码,独立的变量就没办法应付这种情况了,这时可以通过sass的混合器实现大段样式的重用。
为便于书写,@mixin 可以用 = 表示,而 @include 可以用 + 表示。

@mixin rounded-corners { /*定义混合器,目的是添加跨浏览器的圆角边框*/
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}
/*在样式表中通过@include来使用这个混合器,放在你希望的任何地方*/
notice {
  background-color: green;
  border: 2px solid #00aa00;
  @include rounded-corners;
}

/*sass最终生成:*/
.notice {
  background-color: green;
  border: 2px solid #00aa00;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}

如果你发现自己在不停地重复一段样式,那就应该把这段样式构造成优良的混合器.

  1. 混合器中使用css规则:
 @mixin no-bullets {
  list-style: none;
  li { /*混合器中不仅可以包含属性,也可以包含css规则,包含选择器和选择器中的属性*/
    list-style-image: none;
    list-style-type: none;
    margin-left: 0px;
  }
}

ul.plain {
  color: #444;
  @include no-bullets;
}
/*最终,上边的例子如下代码: */

ul.plain {
  color: #444;
  list-style: none;
}
ul.plain li {
  list-style-image: none;
  list-style-type: none;
  margin-left: 0px;
}

如果一个混合器只包含css规则,不包含属性,那么这个混合器就可以在文档的顶部调用.

  1. 给混合器传参
@mixin link-colors($normal, $hover, $visited) {
  color: $normal;
  &:hover { color: $hover; }
  &:visited { color: $visited; }
}

a {
  @include link-colors(blue, red, green);
}

/*Sass最终生成的是:*/

a { color: blue; }
a:hover { color: red; }
a:visited { color: green; }

a {
    @include link-colors( /*这种形式的传参,参数顺序就不必再在乎了,只需要保证没有漏掉参数*/
      $normal: blue,
      $visited: green,
      $hover: red
  );
}
  1. 赋默认值

为了在@include混合器时不必传入所有的参数,我们可以给参数指定一个默认值。参数默认值使用$name: default-value的声明形式,默认值可以是任何有效的css属性值,甚至是其他参数的引用

@mixin link-colors($normal, $hover: $normal, $visited: $normal)
{
  color: $normal;
  &:hover { color: $hover; }
  &:visited { color: $visited; }
}

//如果像下边这样调用:@include link-colors(red) $hover和$visited也会被自动赋值为red。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

the_lower

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值