IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    CSS中的嵌套写法(CSS Nesting)

    Veen Zhao发表于 2024-05-28 14:52:00
    love 0

      近日,在刷蓝桥杯中的模拟实战赛时,有这么一道题:叫“汽车私人定制”,题目链接如下。https://www.lanqiao.cn/problems/18456/learning/?contest_id=187

      打开css的文件,可以看到代码都是类似scss这种:

    lwynpk1r.png

      最开始以为是使用了什么预编译的技术方案,后来才知道,原来原生浏览器已经开始支持css嵌套语法了,关键词是CSS Nesting。
      2024年,可以看到基本上市面上大部分主流浏览器都支持CSS Nesting,也就是说这确确实实成为了一种既定的规范。

    lwynt95v.png

    语法

    /* 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 */
    }

      可以看到语法规则和less、scss非常类似。了解更多可以参考MDN:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_nesting/Using_CSS_nesting

    注意事项

    虽然语法很类似,但需要注意:

    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 解释,& 选择只会被当做 选择器 来使用

    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 */
      }
    }

      但这里要注意,不同浏览器处理的结果可能会有不一致的情况,比如下面这个例子:

    <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>

      在我本机的Chrome和Firefox上表现不一致,Firefox和MDN描述的是一致的。
    lwyoecui.png

    最后想说的

      在web发展的过程中,有很多API都是浏览器吸收了开源社区的热门库后出现的,比如 document.querySelector 吸收了 jQuery 的精华,或者Promise,JSON的相关API都是先出现在社区,然后被浏览器原生支持。今天的css原生嵌套也是借鉴了less,sass等社区方案而出现的。这才是共同进步。



沪ICP备19023445号-2号
友情链接