"# 在Less中什么是&combinator?
在Less中,&符号用于引用当前选择器,通常用于组合选择器(combinator)。组合选择器定义了元素之间的关系,包括子元素、相邻元素等。
1. 基本用法
&可以与组合选择器一起使用,构建复杂的选择器。例如:
.button {
color: blue;
&-primary { // 生成 .button-primary
background-color: green;
}
&-secondary { // 生成 .button-secondary
background-color: grey;
}
}
上述代码中,&引用了.button选择器,生成了.button-primary和.button-secondary两个类。
2. 组合选择器
组合选择器用于表示选择器之间的关系。Less支持多种组合选择器,常见的有:
- 后代选择器(descendant combinator):
- 子选择器(child combinator):
> - 相邻兄弟选择器(adjacent sibling combinator):
+ - 一般兄弟选择器(general sibling combinator):
~
2.1 后代选择器
使用&与后代选择器组合,可以指定某个选择器内的所有后代元素。例如:
.nav {
font-size: 16px;
& .item { // 生成 .nav .item
color: black;
}
}
2.2 子选择器
使用&与子选择器组合,表示直接子元素。例如:
.container {
padding: 20px;
& > .item { // 生成 .container > .item
margin: 10px;
}
}
2.3 相邻兄弟选择器
使用&与相邻兄弟选择器组合,表示紧接着的兄弟元素。例如:
.alert {
color: red;
& + .message { // 生成 .alert + .message
margin-top: 10px;
}
}
2.4 一般兄弟选择器
使用&与一般兄弟选择器组合,表示所有后续兄弟元素。例如:
.header {
background: blue;
& ~ .footer { // 生成 .header ~ .footer
color: white;
}
}
3. 嵌套选择器
&也用于嵌套选择器,以创建更具层次性的样式。例如:
.card {
border: 1px solid #ccc;
&.active { // 生成 .card.active
border-color: green;
}
&.inactive { // 生成 .card.inactive
border-color: red;
}
}
4. 伪类和伪元素
&还可以与伪类和伪元素结合使用。例如:
.button {
color: white;
&:hover { // 生成 .button:hover
background-color: darkblue;
}
&::after { // 生成 .button::after
content: \"➜\";
}
}
5. 结论
在Less中,& combinator是一个强大的工具,可以帮助您构建更具结构性和可维护性的CSS。通过灵活使用&,可以轻松地创建复杂的选择器结构,提高代码的可读性和可维护性。"