0

In a case I'm unable to alter the hierarchy of DOM-element. I'm facing a situation where I have a button, based on 3 spans (button-left, button-content, button-right).

<span class="button-left"></span>
<span class="button-content">My button</span>
<span class="button-right"></span>

When .button-content:hover is activated I'd also like to activate .button-left:hover and .button-right:hover. Can this be done purely by CSS? I know it can be done using jQuery, but I'm looking for a CSS-only solution in this case.

3 Answers 3

1

This could be done if all element is after your hover element via pure css like this

.button-content:hover, .button-content:hover + .button-right{background: red;}

demo

But we can't select the previous element with css.

If you can wrap all your span with a div, it could be easy like this

div:hover > span{background: red;}

demo

1
  • I figured that out as well. Thanks for mentioning siblings. Haven't heard of them before.
    – Ben
    Aug 15, 2013 at 8:25
1

Take a look at css sibling.

.button-content {
    background-color: yellow;
}
.button-right {
    background-color: grey;
}
.button-content:hover {
    background-color: blue;    
}

.button-right:hover, .button-content:hover+.button-right {
    background-color: pink;    
}

Demo

0

Can you target the parent link hover action and do something based on that?

<a class="button">
    <span class="button-left">one</span>
    <span class="button-content">My button</span>
    <span class="button-right">three</span>
</a>

a.button:hover .button-left    { background-color: red; }
a.button:hover .button-content { background-color: red; }
a.button:hover .button-right   { background-color: red; }

demo: http://jsfiddle.net/Xp5e8/

2
  • Unfortunately I can't alter the structure, and for the purpose it's not desired to manipulate the DOM on the fly.
    – Ben
    Aug 15, 2013 at 8:24
  • I don't think you need to alter the DOM - the spans must sit inside something (presumably a link tag)? I'm suggesting that you look at the parent tag and simply target the hover on that instead (but I'm assuming that it has a consistent class or an id associated with it). Aug 15, 2013 at 8:42

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.