快速入门
概览
变量(Variables)
混入(Mixins)
嵌套(Nesting)
运算(Operations)
转义(Escaping)
函数(Functions)
命名空间和访问符
映射(Maps)
作用域(Scope)
注释(Comments)
导入(Importing)
使用 Less.js
命令行用法
浏览器使用
Less.js选项
预加载插件
程序化使用
API
为 Less.js 做贡献
Less 函数手册
逻辑函数
字符串函数
列表函数
数学函数
类型函数
杂项函数
颜色定义函数
颜色通道函数
颜色操作函数
颜色混合函数
进阶指南
变量
父选择器
继承
合并
Mixins
CSS Guards
分离规则集
@import At-Rules
@plugin At-Rules
Maps (NEW!)
作用域
父选择器 - Less入门文档 - 笔下光年
网站首页
父选择器
用 `&` 引用父选择器 操作符 `&` 表示嵌套规则的父选择器,最常用于对现有选择器应用修改类或伪类: ```less a { color: blue; &:hover { color: green; } } ``` 结果: ```less a { color: blue; } a:hover { color: green; } ``` 请注意,如果没有 `&`,上面的示例就会产生 `:hover` 规则(匹配 `<a>` 标记内悬停元素的后代选择器),而这并不是我们使用嵌套 `:hover` 时通常想要的结果。 "父选择器" 操作符有多种用途。基本上,任何时候都可以将嵌套规则的选择器以默认方式以外的其他方式组合起来。例如,`&` 的另一个典型用途是生成重复的类名: ```less .button { &-ok { background-image: url("ok.png"); } &-cancel { background-image: url("cancel.png"); } &-custom { background-image: url("custom.png"); } } ``` 输出: ```less .button-ok { background-image: url("ok.png"); } .button-cancel { background-image: url("cancel.png"); } .button-custom { background-image: url("custom.png"); } ``` ### 多个 & `&` 可以在一个选择器中出现多次。这样就可以在不重复父选择器名称的情况下重复引用父选择器。 ```less .link { & + & { color: red; } & & { color: green; } && { color: blue; } &, &ish { color: cyan; } } ``` 将输出: ```less .link + .link { color: red; } .link .link { color: green; } .link.link { color: blue; } .link, .linkish { color: cyan; } ``` 请注意,`&` 表示所有父选择器(而不仅仅是最近的祖级),因此下面的示例中,`&` 表示所有父选择器: ```less .grand { .parent { & > & { color: red; } & & { color: green; } && { color: blue; } &, &ish { color: cyan; } } } ``` 结果是: ```less .grand .parent > .grand .parent { color: red; } .grand .parent .grand .parent { color: green; } .grand .parent.grand .parent { color: blue; } .grand .parent, .grand .parentish { color: cyan; } ``` ### 更改选择器顺序 在继承的(父)选择器前加上一个选择器可能很有用。这可以通过在当前选择器后面加上 `&` 来实现。例如,在使用 Modernizr 时,您可能希望根据支持的功能指定不同的规则: ```less .header { .menu { border-radius: 5px; .no-borderradius & { background-image: url('images/button-background.png'); } } } ``` 选择器 `.no-borderradius` `&` 将把 `.no-borderradius` 添加到其父级 `.header` `.menu` 中,从而在输出时形成 `.no-borderradius` `.header` `.menu` : ```less .header .menu { border-radius: 5px; } .no-borderradius .header .menu { background-image: url('images/button-background.png'); } ``` ### 组合爆炸 `&` 也可用于在逗号分隔的列表中生成各种可能的选择器排列: ```less p, a, ul, li { border-top: 2px dotted #366; & + & { border-top: 0; } } ``` 这将扩展到指定元素的所有可能(16 种)组合: ```less p, a, ul, li { border-top: 2px dotted #366; } p + p, p + a, p + ul, p + li, a + p, a + a, a + ul, a + li, ul + p, ul + a, ul + ul, ul + li, li + p, li + a, li + ul, li + li { border-top: 0; } ```
上一篇:
变量
下一篇:
继承