“&#my-id”在CSS或SASS中是什么意思?

时间:2018-08-10 18:44:07

标签: css sass

我继承了一些CSS代码,该代码使用ID名称之前的&字符设置样式。看起来像这样:

&#my-id {
  // Content and attributes
}

它也有其他实例,例如:

&:before {
  // content and attributes
}

&:hover {
      // content and attributes
    }

这些是什么意思?我找不到在搜索中表达这一点的好方法,因此我什么也找不到。如果这是重复的话,我表示歉意。

2 个答案:

答案 0 :(得分:3)

它是指父选择器。

输入:

.parent {
    &.child {
        color: red;
    }
}

输出:

.parent.child { color: red }

如果您以BEM格式编写CSS,这将非常有用,例如:

.block {
    &__element {

        width: 100px;
        height: 100px;

        &--modifier {
             width: 200px;
        }
    }
}

.block__element { width: 100px; height: 100px;}
.block__element--modifier { width: 200px;}

<div class="block__element"></div>
<div class="block__element block__element--modifier"></div>

最后,我共享的所有示例都在串联类名,但是您也可以将其用作引用,例如:

.parent {
    & .child {
         color: red;
    }
}

.parent {
    .child & {
         color: blue;
    }
}


.parent .child { color: red }
.child .parent { color: blue }

其他参考:

http://lesscss.org/features/#parent-selectors-feature

https://blog.slaks.net/2013-09-29/less-css-secrets-of-the-ampersand/

Using the ampersand (SASS parent selector) inside nested selectors

答案 1 :(得分:1)

这是Sass的内置功能:https://css-tricks.com/the-sass-ampersand/

可以在嵌套选择器时使用它,并且需要一个更特定的选择器,例如具有两个两个类的元素:

如果您的CSS如下所示:

.some-class.another-class { }

您想嵌套,Sass等效项是:

.some-class {
     &.another-class {}
}