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 表示使用当前元素的文字颜色
  • 这种多重 & 的嵌套写法在组件库开发中很常见,用于创建强作用域的样式
相关推荐
Hilaku1 分钟前
深入WeakMap和WeakSet:管理数据和防止内存泄漏
前端·javascript·性能优化
Juchecar4 分钟前
常见的 HTML 标签及 CSS 选择器速查表
前端
前端程序猿i17 分钟前
用本地代理 + ZIP 打包 + Excel 命名,优雅批量下载跨域 PDF
前端·javascript·vue.js·html
Danny_FD26 分钟前
Vue2 中使用vue-markdown实现编辑器
前端·javascript·vue.js
用户游民26 分钟前
Flutter 项目热更新加载 libapp.so 文件
前端
coding随想26 分钟前
Vue和React对DOM事件流的处理方法解析
前端
用户479492835691527 分钟前
字节面试官:forEach 为什么不能被中断?
前端·javascript
ccnocare28 分钟前
window.electronAPI.send、on 和 once
前端·electron
tager33 分钟前
🍪 让你从此告别“Cookie去哪儿了?”
前端·javascript·后端
阿吉被迫了解低代码38 分钟前
前端:“学算法?狗都不... !”
前端