【问题标题】:What does `&#my-id` mean in CSS or SASS?`&#my-id` 在 CSS 或 SASS 中是什么意思?
【发布时间】:2019-01-18 10:01:03
【问题描述】:

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

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

还有其他的例子,比如:

&:before {
  // content and attributes
}

&:hover {
      // content and attributes
    }

这些是什么意思?我在搜索中找不到表达这一点的好方法,所以我找不到任何东西。如果这是重复的,我深表歉意。

【问题讨论】:

  • 注意它们在其他选择器块中的位置。例如。 #something { color:red; &:hover { color:blue; } } - 这应该给你一个线索。编译后得到#something {color:red} #something:hover {color:blue}

标签: css sass


【解决方案1】:

它指的是父选择器。

输入:

.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

【讨论】:

    【解决方案2】:

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

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

    如果你的 CSS 看起来像这样:

    .some-class.another-class { }
    

    而你想嵌套,Sass 等价物是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-19
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2011-04-06
      相关资源
      最近更新 更多