【CSS】CSS-Nesting:CSS 嵌套写法 —— 有望替代 less sass 的原生嵌套
CSS-Nesting
从
Chrmoe112 开始,原生 CSS 就可以支持嵌套语法了(你不会还是旧版本吧????)
语法
/* Without nesting selector */
parent {
  /* parent styles */
  child {
    /* child of parent styles */
  }
}
/* With nesting selector */
parent {
  /* parent styles */
  & child {
    /* child of parent styles */
  }
}
/* the browser will parse both of these as */
parent {
  /* parent styles */
}
parent child {
  /* child of parent styles */
}示例
类选择嵌套
<style>
  .css-nesting-div {
    .css-nesting-p {
      color: greenyellow;
      .css-nesting-i {
        color: yellowgreen;
      }
    }
  }
</style>
<div class="css-nesting-div">
  class
  <p class="css-nesting-p">
    tag p
    <br />
    <i class="css-nesting-i">child tag i</i>
  </p>
  <i>tag i</i>
</div>
  class
  
    tag p
    
    child tag i
  
使用嵌套自身(合理运用 & 选择)
<style>
  .css-nesting-self {
    div {
      color: red;
      /* 转换为 div section div {} */
      section & {
        color: green;
      }
    }
  }
</style>
<div class="css-nesting-self">
  <div>
    child tag div
    <section>
      tag section
      <div>grandchild tag div</div>
    </section>
  </div>
</div>
          child tag div
          
            tag section
             
        
    grandchild tag div
          使用边界
Concatenation is not possible(无法像 less 或 sass 利用父选择器和其他字符串组合)
示例
<style>
  .css-nesting-error-boundary {
    /*can not concatenation*/
    .css-nesting-concatenation {
      &-p {
        color: blue;
      }
    }
  }
</style>
<div class="css-nesting-error-boundary">
    <div class="css-nesting-concatenation">
      <p class="css-nesting-concatenation-p">tag p</p>
    </div>
</div>预期结果:.css-nesting-concatenation .css-nesting-concatenation-p { color: blue; }
实际结果:找不到元素,未生效。
根据 MDN解释,&选择只会被当做选择器来使用
tag p
Invalid nested style rules - (嵌套样式内 遇到无效样式的处理)
如何处理在嵌套模式内无效样式?MDN 中,如下
可以看出示例,在遇到无效样式时,会忽略无效样式,继续解析下一个有效样式。
.parent {
  /* .parent styles these work fine */
  & %invalid {
    /* %invalid styles all of which are ignored */
  }
  & .valid {
    /* .parent .valid styles these work fine */
  }
}注意:在 Chrome 124 和 Firefox 中表现不同,Firefox 中如 MDN 表现一致 
借用上一个示例。左边 Chrome 右边 Firefox 通过图片可发现 两个浏览器之间的表现差异
<style>
  .css-nesting-error-boundary {
    .css-nesting-concatenation {
      & i {
        color: pink;
      }
      &-p {
        color: blue;
      }
      & a {
        color: red;
      }
    }
  }
</style>
<div class="css-nesting-concatenation">
  <i>tag i</i>
  <p class="css-nesting-concatenation-p">tag p</p>
  <a>tag a</a>
</div>本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 kshao-blog-前端知识记录!
 评论















