scss-混合@mixin @include @function

本文详细介绍了SCSS中的@mixin定义,如何使用@include引入混合,包括设置默认参数和处理不确定数量的参数。同时,讲解了@content在@mixin中的应用以及如何定义和调用@function函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@mixin定义

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

父选择器

@mixin clearfix {
  display: inline-block;
  &:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
  }
  * html & { height: 1px }
}

混合多个

@mixin compound {
  @include highlighted-background;
  @include header-text;
}
@mixin highlighted-background { background-color: #fc0; }
@mixin header-text { font-size: 20px; }

@include 引入

page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

参数混合引入(可设置默认值)

@mixin sexy-border($color, $width: 1in) {
  border: {
    color: $color;
    width: $width;
    style: dashed;
  }
}
p { @include sexy-border(blue); }
h1 { @include sexy-border(blue, 2in); }

不确定参数个数,在参数后加 ...

@mixin box-shadow($shadows...) {
  -moz-box-shadow: $shadows;
  -webkit-box-shadow: $shadows;
  box-shadow: $shadows;
}
.shadows {
  @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
/*编译后*/
.shadowed {
  -moz-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
  -webkit-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
  box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
}

定义数组数值,传入数组作为多个参数,传入参数加...

@mixin colors($text, $background, $border) {
  color: $text;
  background-color: $background;
  border-color: $border;
}
$values: #ff0000, #00ff00, #0000ff;
.primary {
  @include colors($values...);
}

标题@content在@mixin中插入内容

将需要插入内容的位置用@content代替

@mixin apply-to-ie6-only {
  * html {
    @content;
  }
}
@include apply-to-ie6-only {
  #logo {
    background-image: url(/logo.gif);
  }
}
/*编译后*/
* html #logo {
  background-image: url(/logo.gif);
}

为便于书写,@mixin 可以用 = 表示,而 @include 可以用+表示

=apply-to-ie6-only
  * html
    @content

+apply-to-ie6-only
  #logo
    background-image: url(/logo.gif)

插入时的变量命名空间,使用时,插入的内容不能拿到mix内部的变量,而是同级以上的才可以取到

$color: white;
@mixin colors($color: blue) {
  background-color: $color;
  @content;
  border-color: $color;
}
.colors {
  @include colors { color: $color; } 
  /*此处的$color 是取的全局的white*/
}
 /*编译后*/
 .colors {
  background-color: blue;
  color: white;
  border-color: blue;
}

@function

函数声明用@function ,一个函数可以含有多条语句,需要调用 @return 输出结果。

$grid-width: 40px;
$gutter-width: 10px;
@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}
#sidebar { width: grid-width(5); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值