CSS / Less / Sass - 在 :hover 时匹配所有以前的兄弟姐妹

CSS / Less / Sass - Match every previous siblings when :hover

在此代码中:

<div id="Container">
  <span class='first'>First</span>
  <span class='second'>Second</span>
  <span class='third'>Third</span>
</div>

我想换颜色,当:hover

  1. 如果 (.first:hover) 那么 .first { color: red; }
  2. 如果 (.second:hover) 那么 .first, .second { color: red; }
  3. 如果 (.third:hover) 那么 .first, .second, .third { color: red; }

没有 JS 这可能吗?我可以接受 CSS 黑客 :)


可能的答案:

  1. @panther 的回答

更难的版本:

<div id="Container">
  <span class='first' style='color: red'>First</span>
  <span class='second' style='color: green'>Second</span>
  <span class='third' style='color: blue'>Third</span>
</div>
  1. 如果 (.first:hover) 那么 .first { color: pink; }
  2. 如果 (.second:hover) 那么 .first, .second { color: pink; }
  3. 如果 (.third:hover) 那么 .first, .second, .third { color: pink; }

答案:

  1. @Armfoot 的回答好像不错:)

在 CSS 中没有先前的同级选择器,但是...您有时可以使用已知的选择器来完成。有时。

<style>
    span {color: #000; display: block;}
    div:hover span {color: #f00;}
    span:hover ~ span {color: #000}
</style>

<div id="FirstSecondThird-Container">
    <span class='first'>First</span>
    <span class='second'>Second</span>
    <span class='third'>Third</span>
</div>

https://jsfiddle.net/45zLdcvr/

它适用于 block spans(当然是浮动的)。 spans 具有默认值 display: inline,当您将 div 悬停在 space 之间时,它会闪烁。

更新:
当每个跨度都有自己的颜色时,您更新了问题,那么它可能是:

span {color: red}
.second {color: green}
.third {color: blue}

span {display: block;}
div:hover span {color: pink;}
span:hover ~ .second {color: green}
span:hover ~ .third {color: blue}

https://jsfiddle.net/45zLdcvr/1/

这就是我认为可以巧妙地实现您想要实现的目标

@mixin color_on_hover($class){

@if $class==first {span:nth-of-type(1){color:red;}}
@else if $class==second {span:nth-of-type(1), span:nth-of-type(2){color:red;}}
@else if $class==third {span:nth-of-type(1), span:nth-of-type(2), span:nth-of-type(3){color:red;}}

}
span.first:hover{
@include color_on_hover(first);
}
span.second:hover{
@include color_on_hover(second);
}
span.third:hover{
@include color_on_hover(third);
}

希望对您有所帮助!

我想出了一个方法 @each in SASS based in :

$containerID: FirstSecondThird-Container;
##{$containerID}:hover span {color:pink} 
@each $spanclass, $spancolor in (first, red), (second, green), (third, blue) {
  ##{$containerID} span:hover ~ .#{$spanclass}, .#{$spanclass} {
    color: #{$spancolor};
  }
}

它有点短,但这是结果(生成 CSS):

#FirstSecondThird-Container:hover span {
  color: pink;
}
#FirstSecondThird-Container span:hover ~ .first, .first {
  color: red;
}
#FirstSecondThird-Container span:hover ~ .second, .second {
  color: green;
}
#FirstSecondThird-Container span:hover ~ .third, .third {
  color: blue;
}

span {display: block;} /* this line was not generated, it's just to place them vertically */
<div id="FirstSecondThird-Container">
  <span class='first'>First</span>
  <span class='second'>Second</span>
  <span class='third'>Third</span>
</div>

它与 panther's fiddle 具有相似的 CSS 规则。

不错的挑战123qwe :)