Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

hover

less

In this code:

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

I want to change color, when :hover.

  1. IF (.first:hover) THEN .first { color: red; }
  2. IF (.second:hover) THEN .first, .second { color: red; }
  3. IF (.third:hover) THEN .first, .second, .third { color: red; }

Is this possible without JS? I can accept CSS Hacks :)


Possible answers:

  1. @panther 's answer

More difficult version:

<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. IF (.first:hover) THEN .first { color: pink; }
  2. IF (.second:hover) THEN .first, .second { color: pink; }
  3. IF (.third:hover) THEN .first, .second, .third { color: pink; }

Answers:

  1. @Armfoot 's answer seems to be good :)
like image 837
123qwe Avatar asked Jun 02 '15 09:06

123qwe


1 Answers

In CSS there is no previous sibling selector, but... you can sometimes do it using known selectors. Sometimes.

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

It works with block spans (of floated, of course). With spans has default display: inline it will blink when you will hover div in space between spans.

UPDATE:
You updated the question when each span has own color, then it could be:

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/

like image 131
pavel Avatar answered Oct 16 '22 22:10

pavel