问题
I'm writing some basic SCSS. But I've noticed appending & before a class, only works in certain circumstances. For example, before elements like "section" or before ":hover, active".
But this never works for me before ".class". Why not?
For example, in the below code, .flex-item styles only apply, if I remove the &. But look at docs/internet, it should work with & in front, no?
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;
}
}
AND HERE'S THE JSX:
I basically want a section, (as that has high applied). And then two flex items, which sit side by side in a row, with the flex container...
<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;
回答1:
Just remove the &
before the .flex-item
:
section {
// your section rules
.flex-item {
// your .flex-item rules
}
}
You only need the &
(parent element reference) in cases where you want to use a pseudo selector, adding classes to the current selector (or partial class names), link a :hover
or doing some other parent selector usage:
a {
// your link styles
&:hover {
// your hover styles
}
}
.button {
// .button styles
&.colored {
// .button.colored styles
}
&-large {
// .button-large styles
}
}
Or for some other parent selector appliances:
section {
// some styles
.parentclass & {
// this will match .parentclass section
}
}
This are just a few examples.
来源:https://stackoverflow.com/questions/50659865/doesnt-work-in-scss-why-not