Open
Description
一直在使用sass,对于父选择器&其实一直都没有系统性学习过,今天认真学习一下这个小知识点。
- &
- 常见用法
- 后缀用法
- Mardown数学公式(Latex公式)语法中的&
https://sass-lang.com/documentation/style-rules/parent-selector
&
在css中,没有固定的父元素选择器,一般都是子元素选择器和小兄弟(紧随其后的同级元素)选择器。
由于sass支持嵌套,对于一些场景需要指明父元素,比如伪类选择器,属性选择器等等,那么在sass中什么代表父元素呢?
&
就是上面这个与符号。
常见用法
父选择器&用来作为外部选择器的引用,这样可以使得外部选择器在复杂方式下也易用,比如增加一个伪类或者为父元素增加一个选择器。
其实使用了父选择器&的情况不是真正意义上的嵌套,&替换为真正的元素时会被展开。
// scss
.alert{
&:hover {
font-weight: bold;
}
[dir=rtl] & {
margin-left: 0;
margin-right: 10px;
}
:not(&) {
opacity: 0.8;
}
}
// css
.alert:hover { font-weight: bold; }
[dir=rtl] .alert { margin-left: 0;margin-right: 10px; }
:not(.alert) { opacity: 0.8; }
注意:最好是将可以嵌套子元素的元素作为&,span&是不被允许的,因为span一般作为最小的层级。
后缀用法
可以使用外部选择器增加后缀实现子选择器。
这对于使用BEM类似理论的人来说很有用,因为这样的class name是非常结构化的。
只要外部选择器以字母数字结尾(类似class,ID以及元素选择器),你可以使用父选择器是增加额外的文字。
// scss
.accordion {
max-width: 600px;
margin: 4rem auto;
width: 90%;
font-family: "Raleway", sans-serif;
background: #f4f4f4;
&__copy {
display: none;
padding: 1rem 1.5rem 2rem 1.5rem;
color: gray;
line-height: 1.6;
font-size: 14px;
font-weight: 500;
&--open {
display: block;
}
}
}
// css
.accordion{
max-width: 600px;
margin: 4rem auto;
width: 90%;
font-family: "Raleway", sans-serif;
background: #f4f4f4;
}
.accordion__copy{
display: none;
padding: 1rem 1.5rem 2rem 1.5rem;
color: gray;
line-height: 1.6;
font-size: 14px;
font-weight: 500;
}
.accordion__copy--open{
display: block;
}
Mardown数学公式(Latex公式)语法中的&
无独有偶, Latex公式语法中换行时也是用 & 来表示的。
$$ \begin{align*}
result &=(x+y)^2 \\
&= x^2+2xy+y^2
\end{align*} $$