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 表示使用当前元素的文字颜色
  • 这种多重 & 的嵌套写法在组件库开发中很常见,用于创建强作用域的样式
相关推荐
徐小夕7 小时前
我用 AI 撸了个开源"万能预览器":浏览器直接打开 Office、CAD 和 3D 模型
前端·vue.js·github
小码哥_常7 小时前
Flutter Android 延迟加载代码指南:提升应用性能的关键
前端
这是个栗子7 小时前
TypeScript(三)
前端·javascript·typescript·react
kvo7f2JTy8 小时前
基于机器学习算法的web入侵检测系统设计与实现
前端·算法·机器学习
北风toto8 小时前
前端CSS样式详细笔记
前端·css·笔记
nanfeiyan8 小时前
git commit
前端
前端精髓10 小时前
移除 Effect 依赖
前端·javascript·react.js
码云之上10 小时前
从一个截图函数到一个 npm 包——pdf-snapshot 的诞生记
前端·node.js·github
码事漫谈11 小时前
AI提效,到底能强到什么程度?
前端·后端
IT_陈寒11 小时前
React hooks依赖数组这个坑差点把我埋了
前端·人工智能·后端