Less &语法解析

前言

最近公司在依托ant-design4封装自己的组件库,有幸作为其中一员参与了开发。主要是将样式向公司的主题相靠近,做了很多的样式修改。也因此学到了之前不知道的一些less用法,记录一下。

父级选择器&

这是css预处理器最常用的符号,主要用来表示父子的嵌套结构。用法官网有详细说明,不做过多说明。主要是通过一段deepSeek的解读来看这个符号更高阶的用法。

这段 Less 代码中的嵌套选择器 &&-horizontal&-dashed:not(&-with-text) 会被编译成以下 CSS 选择器:

css 复制代码
.divider-prefix-cls.divider-prefix-cls-horizontal.divider-prefix-cls-dashed:not(.divider-prefix-cls-with-text) {
  height: 1px;
  background-image: radial-gradient(circle closest-side, currentcolor 98%, transparent 0),
    linear-gradient(90deg, currentcolor 50%, transparent 0);
  background-repeat: repeat-x;
  background-position:
    0 0,
    5px 0;
  background-size:
    10px 100%,
    10px 100%;
}

编译过程解析:

  1. & 符号的作用

    • 在 Less 中,& 代表当前选择器的父级
    • 这里 @{divider-prefix-cls} 是父级选择器(假设编译后是 .divider-prefix-cls
  2. &&-horizontal

    • 第一个 & = .divider-prefix-cls
    • 第二个 & = .divider-prefix-cls
    • -horizontal 是后缀
    • 组合结果:.divider-prefix-cls.divider-prefix-cls-horizontal
  3. &-dashed

    • & = 当前完整选择器(.divider-prefix-cls.divider-prefix-cls-horizontal
    • -dashed 是后缀
    • 组合结果:.divider-prefix-cls.divider-prefix-cls-horizontal.divider-prefix-cls-dashed
  4. :not(&-with-text)

    • & = 当前完整选择器
    • -with-text 是后缀
    • 组合结果::not(.divider-prefix-cls-with-text)

为什么这样设计?

这种写法是为了:

  1. 提高选择器特异性(specificity)确保样式优先级
  2. 精确匹配 同时具有 horizontaldashed 类但无 with-text 类的元素
  3. 避免样式冲突,确保只在特定组合下应用虚线样式

注意:

  • 代码中的 @s 是一个 Less 变量(假设值为 10px
  • currentcolor 表示使用当前元素的文字颜色
  • 这种多重 & 的嵌套写法在组件库开发中很常见,用于创建强作用域的样式
相关推荐
徐小夕几秒前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
Mintopia1 分钟前
Next.js 单元测试究竟该选 JTest 还是 Vitest?
前端·javascript·next.js
Alice-YUE2 分钟前
【CSS学习笔记3】css特性
前端·css·笔记·html
bug_kada3 分钟前
告别页面卡顿!用DocumentFragment打造高性能DOM操作
前端
遂心_4 分钟前
深入浅出 querySelector:现代DOM选择器的终极指南
前端·javascript·react.js
遂心_7 分钟前
DOM元素内容修改全攻略:从innerHTML到现代API的最佳实践
前端·javascript·react.js
溯水流光8 分钟前
React 源码解析
前端
睡不着先生8 分钟前
CSS `:has()` 实战指南:让 CSS 拥有“if 逻辑”
css
光影少年11 分钟前
Typescript工具类型
前端·typescript·掘金·金石计划
北风GI15 分钟前
如何在 vue3+vite 中使用 Element-plus 实现 自定义主题 多主题切换
前端