0

我正在写一些基本的 SCSS。但是我注意到在课程之前附加 & 仅在某些情况下有效。例如,在 "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;
4

1 回答 1

1

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

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

&在您想要使用伪选择器、将类添加到当前选择器(或部分类名)、链接 a:hover或执行其他一些父选择器用法的情况下,您只需要(父元素引用):

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
    }
}

这只是几个例子。

于 2018-06-02T20:49:42.153 回答