HTML:
<div id="carousel" class="slider__container">
<div class="slider__slide">
<span>Slide One</span>
</div>
<div class="slider__slide--active">
<span>Slide Two</span>
</div>
<div class="slider__slide">
<span>Slide Three</span>
</div>
</div>
SCSS:
body {
background-color: #7e57c2;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.slider__container {
background: red;
min-height: 250px;
width: 200px;
position: relative;
}
.slider__slide {
background: blue;
position: absolute;
height: 100%;
width: 100%;
opacity: 0;
&--active {
opacity: 1; // Why doesn't this inherit the background colour and all other styles?
}
}
我不知道我是否以错误的方式使用&
运算符,但是如果您查看slider__slide
的样式以及其中的&--active
的样式。为什么&--active
不继承slider__slide
中定义的所有其他样式?
您可以签出代码笔here
答案 0 :(得分:2)
这不是它的工作方式。应用&运算符意味着,还必须设置其他类!这不是字符串连接。
这样的代码:
.slider__slide {
&.--active {
opacity: 1;
}
}
将转换为该CSS:
.slider__slide.--active {
color: blue;
}
将应用于此标记代码:
<!--markup with two classes 'slider__slide' and '--active'-->
<div class="slider__slide --active">
但不此标记代码:
<!--markup with single class 'slider__slide--active'-->
<div class="slider__slide--active">
另请参阅updated pen
答案 1 :(得分:2)
因为有两个不同的类,.slider__slide
和.slider__slide--active
。
在这种情况下,您必须继承父类
.slider__slide {
background: blue;
position: absolute;
height: 100%;
width: 100%;
opacity: 0;
&--active {
@extend .slider__slide;
opacity: 1;
}
}
或另一种方式,您必须使用两个类来修改元素:
<div class="slider__slide slider__slide--active"
答案 2 :(得分:1)
您需要在活动状态中添加全名,这样才能正常工作
.slider__slide {
background: blue;
position: absolute;
height: 100%;
width: 100%;
opacity: 0;
&.slider__slide--active {
opacity: 1;
}
}
答案 3 :(得分:0)
简单说明
SCSS
.some-class {
width: 100px;
height: 200px;
&--modified {
height: 300px;
}
}
这将类似于CSS中的SCSS代码
.some-class {
width: 100px;
height: 200px;
}
.some-class--modified {
height: 300px;
}
如果在HTML中仅使用“ .some-class--modified”,则显然不会从“ .some-class”中添加“ width”,因为它们是完全不同的类。
答案 4 :(得分:0)
这是因为您在background: blue;
类而不是.slider__slide
上应用了.slider__slide--active
。
您还应该使用父类,然后使用它的修饰符
<div class="slider__slide slider__slide--active">
,因此它也继承了父样式。
答案 5 :(得分:0)
在要使用活动类的类中使用&:active 。
.slider__slide {
background: blue;
position: absolute;
height: 100%;
width: 100%;
opacity: 0;
&:active {
//styles when active
}
&:hover{
// styles when hovered
}
}