css - &.在 SCSS 中不起作用……为什么不呢?

标签 css sass flexbox styling scss-lint

我正在编写一些基本的 SCSS。但我注意到在类(class)前附加 & 仅在某些情况下有效。例如,在“section”或“:hover, active”等元素之前。

但是在“.class”之前,这对我不起作用。为什么不呢?

例如,在下面的代码中,.flex-item 样式只适用,如果我删除 &。但是看看 docs/internet,它应该与前面的 & 一起工作,不是吗?

section {
  padding: 20px;
  margin: 0 auto;
  border: 1px solid red;
  position: relative;
  width: 95%;
  list-style: none;
  top: 100px;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content: center;


  &.flex-item {
    border: 1px solid green;
    padding: 5px;
    width: 50%;
    height: 150px;
    margin-top: 10px;

    line-height: 150px;
    color: $white;
    font-weight: bold;
    font-size: 3em;
    text-align: center;
  }
}

这是 JSX:

我基本上想要一个部分,(因为它有很高的应用)。然后是两个 flex 元素,它们并排排成一排,带有 flex 容器......

   <section className="flex-container">
    <div className="flex-item">
      <h1>A cashback credit card for holiday and home</h1>
      <ul className="pros">
        <li>No fees for making purchases abroad</li>
        <li>Nothing added on top of the Mastercard exchange rate</li>
        <li>Manage your holiday spending with realtime in-app notifications</li>
        <li>0.5% cashback on all purchases above £1</li>
        <li>Friendly customer support from anywhere with with in-app chat</li>
      </ul>
      <p>Great the same great rewards on holiday and at home with the Travel Cashback Credit Card.</p>
      <p>See full information</p>

      <Link to="/page-2/">Go to page 2</Link>
    </div>
    <div className="flex-item">
      <h1>Hi people</h1>
      <p>Welcome to your new Gatsby site.</p>
      <p>Now go build something great.</p>
      <Link to="/page-2/">Go to page 2</Link>
    </div>
  </section>
);

export default IndexPage;

最佳答案

只需删除 .flex-item 之前的 &:

section {
    // your section rules
    .flex-item {
        // your .flex-item rules
    }
}

你只需要在你想使用伪选择器的情况下使用&(父元素引用),将类添加到当前选择器(或部分类名),链接一个:悬停 或做一些其他的父选择器用法:

a {
    // your link styles
    &:hover {
        // your hover styles
    }
}

.button {
    // .button styles
    &.colored {
        // .button.colored styles
    }
    &-large {
        // .button-large styles
    }
}

或者对于其他一些父选择器组件:

section {
    // some styles
    .parentclass & {
         // this will match .parentclass section
    }
}

这只是几个例子。

关于css - &.在 SCSS 中不起作用……为什么不呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50659865/

相关文章:

html - Flexbox 行左对齐

javascript - 在 Webpack 模块中解析 SCSS 文件

javascript - vue自定义导入css(sass)文件

html - 如何将表单与 flex 对齐

javascript - 自动将 float div 的宽度固定为图像大小

css - 带有 sass 的原始 CSS 样式表

twitter-bootstrap - 可扩展的布局过渡

html - CSS FLOAT LEFT - 无法让两个 div 并排

html - 使用 css 裁剪和居中图像

asp.net - 在数据列表中的两列之间放置固定空间