Sass中@at-root嵌套

at-root:是Sass3.3.0中新增的功能,用来跳出选择器嵌套的。默认所有的嵌套,继承所有上级选择器,但有了这个就可以跳出所有上级选择器。

1、普通跳出嵌套

Sass编译

//没有跳出
.parent-1 {
    color:#f00;
    .child {
        width:100px;
    }
}

//单个选择器跳出
.parent-2 {
    color:#f00;
    @at-root .child {
        width:200px;
    }
}

//多个选择器跳出
.parent-3 {
    background:#f00;
    @at-root {
        .child1 {
            width:300px;
        }
        .child2 {
            width:400px;
        }
    }
}

css输出

.parent-1 {
  color: #f00;
}

.parent-1 .child {
  width: 100px;
}

.parent-2 {
  color: #f00;
}

.child {
  width: 200px;
}

.parent-3 {
  background: #f00;
}

.child1 {
  width: 300px;
}

.child2 {
  width: 400px;
}

@at-root (without: …)和@at-root (with: …)

默认@at-root只会跳出选择器嵌套,而不能跳出@media或@support,如果要跳出这两种,则需使用@at-root (without: media),@at-root (without: support)。这个语法的关键词有四个:

1、all(表示所有)
2、rule(表示常规css)
3、media(表示media)
4、support(表示support,因为@support目前还无法广泛使用,所以在此不表)。

我们默认的@at-root其实就是@at-root (without:rule)。

scss编译

/*跳出父级元素嵌套*/
@media print {
    .parent1{
        color:#f00;
        @at-root .child1 {
            width:200px;
        }
    }
}

/*跳出media嵌套,父级有效*/
@media print {
    .parent2{
        color:#f00;
        @at-root (without: media) {
            .child2 {
                width:200px;
            }
        }
    }
}

/*跳出media和父级*/
@media print {
    .parent3{
        color:#f00;
        @at-root (without: all) {
            .child3 {
                width:200px;
            }
        }
    }
}

CSS输出:

@charset "UTF-8";
/*跳出父级元素嵌套*/
@media print {
  .parent1 {
    color: #f00;
  }
  .child1 {
    width: 200px;
  }
}

/*跳出media嵌套,父级有效*/
@media print {
  .parent2 {
    color: #f00;
  }
}

.child2 {
  width: 200px;
}

/*跳出media和父级*/
@media print {
  .parent3 {
    color: #f00;
  }
}

.child3 {
  width: 200px;
}

@at-root与 & 配合使用

.child{
    @at-root .parent &{
        color:#f00;
    }
}

css输出

.parent .child {
  color: #f00;
}

应用于@keyframe

scss编译

.demo {
    animation: motion 3s infinite;
    @at-root {
        @keyframes motion {

        }
    }
}

css输出

.demo {
  animation: motion 3s infinite;
}
@keyframes motion {}.parent .child {
  color: #f00;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值