CSS中的嵌套写法(CSS Nesting)

CSS中的嵌套写法(CSS Nesting)

当前文章收录状态:
查询中...

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

图片[1]-CSS中的嵌套写法(CSS Nesting)-明恒博客

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

图片[2]-CSS中的嵌套写法(CSS Nesting)-明恒博客

语法

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

可以看到语法规则和lessscss非常类似。了解更多可以参考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>

在我本机的ChromeFirefox上表现不一致,FirefoxMDN描述的是一致的。

图片[3]-CSS中的嵌套写法(CSS Nesting)-明恒博客

最后想说的

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

© 版权声明
THE END
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=270198dipw4ko
点赞9赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容