为什么 CSS 嵌套同级组合器在以下示例中无法正确应用?

问题描述 投票:0回答:1
<div class='splash yellow'>
  <span>Yellow</span>
</div>
<div class='splash green'>
  <span>Green</span>
</div>
<div class='splash red'>
  <span>Red</span>
</div>
.splash {
    margin: 15px;
  
    + .red {
        background-color: red;
    }
    + .green {
        background-color: green;
    }
    + .yellow {
        background-color: yellow;
    }
}

https://jsfiddle.net/8e27qyc9/2/

为什么黄色背景没有像小提琴示例中的红色和绿色那样应用?是什么导致了这种行为?

css nested siblings
1个回答
0
投票

我混淆了同级选择器和复合选择器。

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_nesting/Using_CSS_nesting#concatenation_is_not_possible

解决方案:

.splash {
    margin: 15px;
  
    .red& {
        background-color: red;
    }
    .green& {
        background-color: green;
    }
    .yellow& {
        background-color: yellow;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.