cabellicar123 cabellicar123 - 4 months ago 10
HTML Question

Use CSS To Cause Hover On One Object to Affect Another

Using pure CSS I want an image to appear when hovering over text:

HTML

<h1 id="hover">Hover over me</h1>
<div id="squash">
<img src="http://askflorine.com/wp-content/uploads/2013/10/temp_quash.jpg" width="100%">
</div>


CSS

#squash {
display: none;
}

#hover:hover + #squash {
display: block;
}


This works fine unless I put something in between the
<h1>
and the
<div>
. I know this is because of the CSS selector I am using (
+
). How could I use an event on one tag to cause a change in CSS on another?

P.S. Here's a jsfiddle: https://jsfiddle.net/r0ccynkx/

Answer

You can use the General Sibling Selector ~ selector instead of the Adjacent Sibling Selector + selector, like this:

#hover:hover ~ #squash {
  display: block;
}

JSFiddle

You can read more about different CSS sibling selectors here.