【CSS】SCSS混合的使用

基本使用

Scss中的混合允许定义一组 CSS 规则,然后在不同部分重用这些规则

@mixin flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box1 {
  @include flex;
}

.box2 {
  @include flex;
}

与变量不同,混合不仅可以包含样式规则,还可以包含参数

@mixin flex($layout) {
  display: flex;
  justify-content: $layout;
  align-items: $layout;
}

.box1 {
  @include flex(start);
}
.box2 {
  @include flex(center);
}

支持声明默认参数,使用时也可以指定某参数

@mixin flex($justify-content: center, $align-items: center) {
  display: flex;
  justify-content: $justify-content;
  align-items: $align-items;
}

.box1 {
  @include flex;
}
.box2 {
  @include flex(space-between, start);
}
.box3 {
  @include flex($align-items: start);
}

通过 @content 在混合中动态注入样式

@mixin flex($justify-content: center, $align-items: center) {
  display: flex;
  justify-content: $justify-content;
  align-items: $align-items;
  @content;
}

.box1 {
  @include flex() {
    gap: 20px;
  }
}
.box2 {
  @include flex(center, start) {
    gap: 10px;
  }
}

可以使用条件语句

@mixin theme-color($theme) {
  @if $theme == "dark" {
    background-color: black;
    color: white;
  } @else if $theme == "light" {
    background-color: white;
    color: black;
  } @else {
    background-color: gray;
    color: white;
  }
}

title {
  @include theme-color(dark);
}

示例

媒体查询确定样式

@mixin respondTo($breakname) {
  @if$breakname == "phone" {
    @media (min-width: 320px) and (max-width: 480px) {
      @content;
    }
  } @else if$breakname == "pad" {
    @media (min-width: 481px) and (max-width: 768px) {
      @content;
    }
  }
}

.header {
  width: 100%;
  @include respondTo("phone") {
    height: 50px;
  }
  @include respondTo("pad") {
    height: 60px;
  }
}

通过 scss 的 mapmap-get 优化代码

$breakpoints: (
  "phone": (
    320px,
    480px,
  ),
  "pad": (
    481px,
    768px,
  ),
  "notebook": (
    769px,
    1024px,
  ),
  "desktop": (
    1025px,
    1440px,
  ),
  "tv": 1441px,
);

@mixin respondTo($breakname) {
  $bp: map-get($breakpoints, $breakname);
  @if type-of($bp) == "list" {
    // 从数组中取出min和max
    $min: nth($bp, 1);
    $max: nth($bp, 2);
    @media (min-width: $min) and (max-width: $max) {
      @content;
    }
  } @else {
    @media (min-width: $bp) {
      @content;
    }
  }
}

.header {
  width: 100%;
  @include respondTo("phone") {
    height: 50px;
  }
  @include respondTo("pad") {
    height: 60px;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

田本初

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

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

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

打赏作者

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

抵扣说明:

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

余额充值