NotMe NotMe - 28 days ago 8
HTML Question

How can I have a CSS hover affect a different tag?

Let's say I have the following:

<style>
.myLabel {
color: blue;
}
.myLabel:hover {
color:red;
}
</style>
<div>
<img src='myimage.png' />
<span class='myLabel'>Image Label</span>
</div>


Is it possible to replace the image (also via css) when they hover over the span? If so, how could I do that?

Answer Source

There don't seem to be any sibling selector for previous siblings.

W3 defined adjacent siblings and some browser support seems to be available for general siblings -- but, both are for following sibling(s).

So, I think you'll find it easier to accomplish with :hover set to the div.

And, I've never heard of CSS being capable of altering a src attribute. About the only way I can think that might work to alter an image via CSS is to have src a transparent image and alter background-image.

<style>
    .myLabel img { background-image: url('...'); }
    .myLabel span { color: blue; }
    .myLabel:hover img { background-image: url('...'); }
    .myLabel:hover span { color:red; }
</style>
<div class='myLabel'>
    <img src='transparent.png' />
    <span>Image Label</span>
</div>