1

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?

JSFiddle

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
carloabelli
  • 4,289
  • 3
  • 43
  • 70

3 Answers3

2

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.

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
  • Okay. Is there a way to still have it work for say in this case where the image is placed before? https://jsfiddle.net/b5bn5c6u/1/ – carloabelli Jul 20 '16 at 17:25
  • Sadly not, there is not such thing as a previous sibling selector. It would have to come after the element. http://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector – Hunter Turner Jul 20 '16 at 17:27
0

Please try this

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

#squash {
  display: none;
}

#hover:hover ~ #squash {
  display: block;
}
vignesh
  • 951
  • 5
  • 13
-1

Depends on what you put in between the 2 parts. If text encase squash inside the

<p> text here
    <div id="squash"...>
    </div>
</p>

Then css changes to

#hover:hover + p #squash {
bdt
  • 1
  • That won't work. You can't put a `div` inside a `p`, so the code won't work as expected. Check if your solutions work before posting them. – Mr Lister Jun 02 '19 at 17:28