Jon
Jon

Reputation: 8531

Change Text Colour When Hovering Over Another Element on the Same Level

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>

Upvotes: 1

Views: 182

Answers (3)

Josh Crozier
Josh Crozier

Reputation: 240978

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.

Upvotes: 1

Duver
Duver

Reputation: 500

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?

Upvotes: 0

j08691
j08691

Reputation: 207900

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

Upvotes: 0

Related Questions