Sass語法--嵌套

選擇器嵌套

body {
    margin:0;
    header{
        margin:5px;
    }
}

編譯之後>>>>

body {
  background-color: lightgray;
 }
body header {
    background-color: lightgreen; 
 }

屬性嵌套

footer{
    background:{
      color:red;
      size : 100% 50%;
      position: center;
    }
  }

編譯之後>>>>

body footer {
    background-color: red;
    background-size: 100% 50%;
    background-position: center; }

hover和內部class

body{
    a:hover {
    color: red;
  }
  span {
    &:hover {
      color: blue;
    }
    color: red;
    //內部class
    //注意&.content 和  .content的區別
    &.content { color:green; }
    .content2 {color:red;}
  }
}

編譯之後>>>

body a:hover {
    color: red;
}
body span {
    color: red;
}
body span:hover {
    color: blue;
}
/*這是 &.content*/
body span.content {
    color: green;
}
/*這是 .content*/
body span .content2 {
    color: red;
}

@at-root :意思是跳出根部嵌套選擇器

body{
    @at-root .container{
    width:995px;
  }
}
//編譯之後

.container {
   width: 995px;
}
//就不會包含在body裏面了

注意 如果是在@medio裏面

body {
    @media screen and (max-width:600px){
    .content4 {
      color:#000;
    }
    //跳出了media 但是沒跳出body
    @at-root (without : media){
      .content3{
        color:#ccc; 
    }
    }
    //跳出了body
    @at-root (without : media rule){
      .content5{
        color:#ccc; 
    }
    }
  }
}

編譯之後>>>

@media screen and (max-width: 600px) {
   body .content4 {
          color: #000;
      }
}
body .content3 {
  color: #ccc;
}
.content5 {
  color: #ccc;
}

需要注意

.foo {
    @at-root .bar {
        color: gray;

        @at-root button{
            color:red;

            @at-root span {
                color: orange;
            }
        }
    }
}

//編譯之後

.bar {
  color: gray; 
}
button {
  color: red; 
}
span {
  color: orange; 
}

默認@at-root只會跳出選擇器嵌套,而不能跳出@media或@support,如果要跳出這兩種,則需使用@at-root(without: media),@at-root(without :support)。這個語法的關鍵字有四個: all(表示所有),rule(表示常規css),media,support。默認的@at-root其實就是@at-root(without : rule)

@at-root 與 &

@at-root .text-info{
    color:red;
    @at-root nav &{
      color:blue;
    }
  }
  //編譯後
.text-info {
    color: red;
}
nav .text-info {
    color: blue;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章