Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to hide the hovered image and show another image using only CSS?

Tags:

html

css

image

My problem is that I have 2 images; #two is initially hidden.

Is there any way in only CSS (no JS) so that when I hover at #one it gets hidden and #two is shown, possible with some animation

#two{
    display:none;
}
#one:hover + #two{
    display: block;
}
<img id='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoMUKwCL1uINRV035jkpfQzAbiObKqraXA6369mZBe0To0UuWP'>

<img id='two' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSMYIpY4d8KlTzhAd38KZW8DIadeEV59WtLlxeIH3PS4uPXL0RP'>

PS: I am working on a Google Chrome Extension

EDIT: there is idea to use background-image : url() of image and change it on hover, but I don't want it, as it doesn't work, it needs to give full chrome extension path including extension ID

like image 812
Umair Ayub Avatar asked Oct 16 '25 05:10

Umair Ayub


1 Answers

@ATomCalledStu has given the CSS only answer, but that only works if you have a relative wrapper.

What would work even better with any wrapper, is setting the :hover on the wrapper:

.wrapper, img {
  display:inline-block;
}
#two {
  display:none;
}
.wrapper:hover #two {
  display: inline-block;
}
.wrapper:hover #one {
  display: none;
}
<div class="wrapper">
  <img id='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoMUKwCL1uINRV035jkpfQzAbiObKqraXA6369mZBe0To0UuWP'>

  <img id='two' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSMYIpY4d8KlTzhAd38KZW8DIadeEV59WtLlxeIH3PS4uPXL0RP'>
</div>

If you alter somebody's website, you can probably see that the images most likely have a wrapper element (div, span, anything) and use that to set the :hover selector.

I usually want to avoid position:absolute unless I am absolutely sure that the behavior never relies on relative positioning. In this case, especially because I don't know what your page looks like, the chances that absolute does not work seems very likely.

Update:

If you want an animation, you are probably best off with position:absolute as the previous answer suggested. Sorry for the confusion ;)

like image 185
Randy Avatar answered Oct 17 '25 19:10

Randy