适用范围:

  1. 利用&获取父选择器后, 再跳出父选择器

梗概:

@at-root用来跳出嵌套,在多级嵌套时比较常用,包含withoutwith

语法:

@at-root(without: 嵌套类型)

1. 说明:

  1. 嵌套类型可以有以下四种
    1. all 表示所有;
    2. rule 表示常规css选择器;
    3. media 表示media
    4. support表示support@support主要是用于检测浏览器是否支持css的某个属性)。
  2. (without: 嵌套类型)可省, 默认为(without: rule)

实例:

1. 跳出css选择器

.parent-3 {
    background:#f00;
    @at-root {
        .child1 {
            width:300px;
        }
        .child2 {
            width:400px;
        }
    }
}

编译为

.parent-3 {
    background: #f00;
}
.child1 {
    width: 300px;
}
 
.child2 {
    width: 400px;
}

2. 跳出@media

/*跳出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;
            }
        }
    }
}

编译成

/*跳出media嵌套,父级有效*/
@media print {
    .parent2 {
        color: #f00;
    }
}
.parent2 .child2 {
    width: 200px;
}
/*跳出media和父级*/
@media print {
    .parent3 {
        color: #f00;
    }
}
.child3 {
    width: 200px;
}

3. @at-root与 & 配合使用

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

编译成

.parent .child {
    color: #f00;
}

4. 应用于@keyframe

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

编译成

.demo {
    animation: motion 3s infinite;
}
@keyframes motion {}