0

I have always wonder why this wouldn't work as it would make so much sense.

CSS:

#button1:hover {
    background: green;
    #button2 {
        background: red;
    }
}

HTML

<button id="button1"></button>
<button id="button2"></button>

If I hover over Button1, Button2's background should also change.

Is there a workaround to this other than the use of Javascript?

3
  • Have a look at all the possible selectors.
    – Jeroen
    Nov 21, 2014 at 0:35
  • 1
    Your code would be valid with a preprocessor like SASS -> sass-lang.com
    – peppeocchi
    Nov 21, 2014 at 0:41
  • 2
    Indeed it would but it would also not work as he wants since the preprocessor thinks #button1 is a child of #button1. So he should write then instead: & + #button2 { Nov 21, 2014 at 0:51

2 Answers 2

4

You can use the adjacent selector,

#button1:hover {
    Background: green;
}
#button1:hover + #button2 {
    Background: red;
}

Have a look at all the css selectors: http://css-tricks.com/almanac/

Oh by the way it's only possible to apply css on hover to elements after the hovered element. Parent elements and elements before the hovered element cannot be styled with css on hover. It's a limitation of css.

2
  • it does not answer his question.
    – kriyeta
    Nov 21, 2014 at 0:44
  • 1
    he want to add separate color for each button. @seahorsepip
    – kriyeta
    Nov 21, 2014 at 0:51
0

This can be done but CSS lacks the ability to provide powerful conditional statements. However if you look into SASS CSS LESS it is starting to happen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.