scss混合mixin与继承extend的使用(继承篇)

继承(extend)

理解:

包含多个样式的‘变量’,一个正常使用的样式类,不管以后继不继承,都会被编译解析。

若单独为继承而写的样式类,本身不想被编译解析,可以使用占位符%来定义样式类。

解析时是将用了继承样式类的选择器复制到一起,复制的是选择器,而不是定义的样式类。

基本使用:

定义继承:
.box1 {
    /* css 声明 */
}
 
 
使用继承:
.box2{
    @extend .box1;
    ...
}
 
解析格式:
.box, .bo2{
    /* css 声明 */
}

不被编译的继承

定义继承:
%box1 {
    /* css 声明 */
}
 
 
使用继承:
.box2{
    @extend %box1;
    ...
}
 
解析格式:
.bo2{
    /* css 声明 */
}

局限一:作用域

@media指令中只能使用本指令内的继承源

写法一:
.box1{
   width: 200px;
   margin-right: 20px;
   background-color: pink;
}
@media screen and (max-width: 300px){
.box1{
  @extend .box1
}

写法二:
.box1{
   width: 200px;
   margin-right: 20px;
   background-color: pink;
 }
@media screen and (max-width: 300px){
  .box1{
    color: white;
  }
  .box2{
    @extend .box1
  }
}

// 报错:
DEPRECATION WARNING: Passing --sourcemap without a value is deprecated.
Sourcemaps are now generated by default, so this flag has no effect.
      error test.scss (Line 5: You may not @extend an outer selector from within @media.
You may only @extend selectors within the same directive.
From "@extend .box1" on line 19 of test.scss.
)

写法三
@media screen and (max-width: 300px){
  .box1{
    color: white;
  }
  .box2{
    @extend .box1;
    width: 200px;
  }
}

正常编译
@media screen and (max-width: 300px) {
  .box1, .box2 {
    color: white; }

  .box2 {
    width: 200px; } }

局限二:继承源选择器规范

继承源的选择器不支持组合,尽量为单选择器,后代选择器( )和兄弟选择器(+)都不可以作为继承源,继承源解析后是一个名字的选择器,不要是谁的后代或者兄弟姐妹,不然解析后选择器会出现错误。下面是两个例子

// html
<div class="box1">
    <div class="box2"></div>
</div>
<div class="div1">
    <div class="div2"></div>
</div>


// scss 写法一
.box1 .box2{
    width: 100px;
}
.div1 {
    @extend .box2;
    height:100px;
}


// 解析一
.box1 .box2, .box1 .div1 {    // 出错  div1并不是box1的后代
  width: 100px; }

.div1 {
  height: 100px; }


// scss 写法二
.box1 .box2{
    width: 100px;
}
.div1 .div2{
    @extend .box2;
    height:100px;
}


// 解析一
.box1 .box2, .box1 .div1 .div2, .div1 .box1 .div2 {   // 出错
  width: 100px; }

.div1 .div2 {
  height: 100px; }



局限三:不能带参

猜你喜欢

转载自blog.csdn.net/weixin_59128282/article/details/119244896