开发者

Apply css rules to other elements

开发者 https://www.devze.com 2023-03-04 13:03 出处:网络
I don\'t think there is a current SO question addressing this; but if there is please point me to it and I\'ll close this one.

I don't think there is a current SO question addressing this; but if there is please point me to it and I'll close this one.

Anyways, suppose html like this:

<div>
  <div class="a" style="float:left;"></div>
  <div class="b" style="float:left;"></div>
  <div class="c" style="float:left;"></div>
  <div style="clear:both;"></div>
</div>

Is there any css rules I can define which alter the styles of the OTHER elements when hovering. So, something like

  .a:hover {
     // change bg colors of .b and .c
  }

I know I can do开发者_Python百科 this with hover events in javascript; but I was hoping for a css only solution. If you can point to some part of the css spec that says this is NOT possible then I will still mark that as an answer. (Even though I'll admit I didn't read the whole thing; I did read some of it).

EDIT: The answers everyone marked seemm to work and are the correct answer; but they don't work in Chrome/Safari (but IE8 is fine...go figure :P). See here: Why doesn't this CSS selector work: a:hover ~ span?


Is there any css rules I can define which alter the styles of the OTHER elements when hovering

You can use adjacent sibling selectors in this case (since b and c follow a).

.a:hover + .b,
.a:hover + .b + .c { }

You could also use the general sibling combinator from CSS 3

.a:hover ~ div {}

Although this still has the requirement that the element you are hovering is first.

I know I can do this with click events in javascr

mouseover events would make more sense

If you can point to some part of the css spec that says this is NOT possible

Specifications tell you what is possible. They rarely state what can't be done (since providing an exhaustive list of what isn't possible would make all specifications huge)


Use this:

.a:hover + .b,
.a:hover + .b + .c,
{
    // styles of .b and .c
}

More on sibling combinators: http://www.w3.org/TR/css3-selectors/#sibling-combinators


Myabe it will help you a bit:

.a:hover + .b {
     background-color:red;
 }
.a:hover + .b + .c {
    background-color:red;
 }

Watch results: http://jsfiddle.net/uNZSX/

0

精彩评论

暂无评论...
验证码 换一张
取 消