1

I am trying to change the text colour of .foo when the user hovers over .bar and I am unsure how to do this with only CSS. I have tried using the CSS preceding element selector ~ but that did not work.

http://jsfiddle.net/847E2/

<div>
  <p class="foo">Foo</p>
  <ul class="bar"><li>Bar<li></ul>
</div>

.bar:hover~.foo {
    color: red;
}

EDIT - My requirements have changed. I updated my HTML structure to make the .bar a <ul>

Jon
  • 8,205
  • 25
  • 87
  • 146

3 Answers3

1

The sibling selector ~ doesn't select elements preceding it, just elements succeeding it. Thus, when hovering over the element .bar, the element .foo cannot be selected, as it is preceding .bar.

You could do something like this instead:

jsFiddle example

div:hover :not(:hover) {
    color: red;
}

Basically, this is setting the color of the child elements to color:red when hovering over the parent, div. However, it will not be applied on :hover of the element you are on. This makes it seem as though the color is changing when you hover over the sibling element.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • That makes sense. What happens if I modified my HTML structure to where my 2nd `p` (.bar) is now a `ul` instead of a `p`. How would I modify the CSS to achieve the same effect? – Jon Nov 06 '13 at 19:46
  • Might want to note that this is CSS3 and not supported in IE<9. – j08691 Nov 06 '13 at 19:47
  • @JoshC Yup, like that. Let me try integrating that into my code :) – Jon Nov 06 '13 at 20:09
0

The + selector is an adjacent sibling combinator selector allows you to select an element that is directly after another specific element.

It doesn't matter if you use any element if have .bar class name.

NOTE: There is no "previous sibling" selector, that's why i change the elements order in the DOM.

.bar:hover + .foo {
    color: red;
}

Demo http://jsfiddle.net/847E2/11/

Also can see: http://css-tricks.com/child-and-sibling-selectors/

Is there a "previous sibling" CSS selector?

Community
  • 1
  • 1
Duver
  • 500
  • 4
  • 12
0

Here's a way to do it with CSS (no CSS3 needed):

div:hover p{
    color: red;
}
.foo:hover{
    color: black;
}
div:hover p.bar{
    color: black;
}

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272