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 表示使用当前元素的文字颜色
  • 这种多重 & 的嵌套写法在组件库开发中很常见,用于创建强作用域的样式
相关推荐
chao_7892 分钟前
CSS表达式——下篇【selenium】
css·python·selenium·算法
元气小嘉7 分钟前
前端技术小结
开发语言·前端·javascript·vue.js·人工智能
神仙别闹22 分钟前
基于ASP.NET+SQL Server实现(Web)企业进销存管理系统
前端·后端·asp.net
土豆12501 小时前
提升CSS开发效率的必备Chrome插件
css·chrome
江城开朗的豌豆1 小时前
Vue计算属性:为什么我的代码突然变优雅了?
前端·javascript·vue.js
Sun_light1 小时前
5 个理由告诉你为什么有了 JS 还要用 TypeScript
前端·typescript
陈随易1 小时前
Kimi k2发布,效果比肩Sonnet4,价格与DeepSeek一致
前端·后端·程序员
一点一木2 小时前
🚀 2025 年 06 月 GitHub 十大热门项目排行榜 🔥
前端·人工智能·github
杨进军2 小时前
实现 React 函数组件渲染
前端·react.js·前端框架
归于尽2 小时前
被 50px 到 200px 的闪烁整破防了?useLayoutEffect 和 useEffect 的区别原来在这
前端·react.js