5

I'm trying to make a pure CSS image change on hover / rollover without using background images. So far I have one image and when you rollover that image, another image appears. Here is the CSS:

#hidden {
display: none;
}

#visible:hover + #hidden {
display: block;
}

So, when you rollover the #visible div, the #hidden div appears. Here is the jsFiddle: http://jsfiddle.net/MNyzd/1/

This works great, but it is not exactly what I want to accomplish. I would like the images to swap. So when you rollover #visible, it should disappear instead of remaining visible. My first initial idea was to make the #visible div to display:none on hover (#visible:hover display:none;), but this did not work.

So does anyone have any idea how I would successfully turn this into a traditional image hover / swap using this method? Any help would be appreciated and again, here is the jsFiddle... http://jsfiddle.net/MNyzd/1/

Dyck
  • 2,569
  • 4
  • 21
  • 21

3 Answers3

7

Use a container where you do the hover on:

http://jsfiddle.net/MNyzd/8/

.hidden {
    display: none;
}

.container:hover .visible
{
    display: none;
}

.container:hover .hidden {
    display: block;
}

See also this answer: Hide / show content via CSS:hover (or JS if need be)

Community
  • 1
  • 1
Ikke
  • 99,403
  • 23
  • 97
  • 120
3

Like this?

jsFiddle

div {
    cursor:pointer;
    overflow:hidden;
    width:300px;
}
div > img:nth-child(2), div:hover > img:nth-child(1) {
    display:none;
}
div:hover > img:nth-child(2) {
    display:block;
}
Shivam
  • 2,208
  • 3
  • 24
  • 39
0

http://jsfiddle.net/MNyzd/4/

EDIT: The code:

#hidden {
display: none;
position: absolute; 
top: 8px;
left: 8px; 
}

#visible:hover + #hidden {
display: block;
}

#hidden, #visible {
width:300px;
height:300px;
}

<div id="visible"><img src="http://b.vimeocdn.com/ps/372/159/3721596_300.jpg"></div>
<div id="hidden"><img src="http://yuccan.com/wp-content/uploads/2013/04/cool-eez-spaced2.png"></div>
Chad
  • 492
  • 5
  • 14
  • never even thought of using absolute positioning! haha, its like an illusion of some sorts. you should post exactly what you did in your answer bro. (it wont let me accept the answer till 5 mins) – Dyck Aug 09 '13 at 18:54
  • I commented below that ikke's method is probably best. My jsFiddle is not buggy at all so not sure why you'd say that. – Chad Aug 09 '13 at 19:06
  • When I hover over the image, it blinks and on second hover does nothing. I am on Firefox 22.0. – Shivam Aug 09 '13 at 19:08
  • Yes it should not be doing that. Which is why I mentioned it's buggy :-) – Shivam Aug 09 '13 at 19:11
  • But let's face it, it's not my code. It's obviously your browser or a plugin you're using in your browser. – Chad Aug 09 '13 at 19:11
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/35158/discussion-between-shivam-and-chad-p) – Shivam Aug 09 '13 at 19:12