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 表示使用当前元素的文字颜色
  • 这种多重 & 的嵌套写法在组件库开发中很常见,用于创建强作用域的样式
相关推荐
Justin3go1 小时前
两年后又捣鼓了一个健康类小程序
前端·微信小程序
巴巴_羊3 小时前
xss和csrf
前端·xss·csrf
华子w9089258593 小时前
基于 Python Web 应用框架 Django 的在线小说阅读平台设计与实现
前端·python·django
烛阴4 小时前
让你的Python并发飞起来:多线程开发实用技巧大全
前端·python
旺代4 小时前
Vue3中的v-model、computed、watch
前端
excel4 小时前
微信小程序鉴权登录详解 —— 基于 wx.login 与后端 openid 换取流程
前端
Gazer_S4 小时前
【前端隐蔽 Bug 深度剖析:SVG 组件复用中的 ID 冲突陷阱】
前端·bug
蓝婷儿5 小时前
每天一个前端小知识 Day 7 - 现代前端工程化与构建工具体系
前端
mfxcyh6 小时前
npm下载离线依赖包
前端·npm·node.js
waterHBO6 小时前
01 ( chrome 浏览器插件, 立马翻译), 设计
前端·chrome