randomlysid
randomlysid

Reputation: 37

Replace an image with a div on hover

Seems fairly simple, but I can't get it to work.

The div contains facebook / twitter links. The way it should work is that the image is displayed and then when someone hovers on it, it disappears to be replaced by the social icons.

I've got the code to work with text in the div, but as soon as I add images / scripts, it seems to break. (The code I've got doesn't have the image disappearing either, that is something I haven't figured out how to do).

Here's what I've got:

<div class="image">
<img src="/some_image.jpg">

<div class="sharerDiv">
<p>Hello!</p>
</div>
</div>

With the following css:

.sharerDiv {
display:none;
}
img:hover + .sharerDiv {
display:block;
}

Here it is on jsfiddle: http://jsfiddle.net/randomlysid/dxwma/1/

I would like ot do this with css if possible, since that's what I'm familiar with, but if jQuery is the only way to get it done, that works as well.

Thanks!

Upvotes: 3

Views: 261

Answers (3)

Onur Yıldırım
Onur Yıldırım

Reputation: 33644

Change your CSS to this:

.image
{
  width: 80px;
  height: 80px;
}
.sharerDiv
{
  display: none;
  position: absolute;
  z-index: 99;
}
img
{
  position: relative;
  display: block;
}
.image:hover .sharerDiv
{
  display: block;
}
.image:hover img
{
  display: none;
}
  1. Your outer container .image should better have the same bounds (width and height).
  2. The position value of .sharerDiv should be absolute (so it can float).
  3. hover should be applied to the outer container.

Here is an edited fork of your code on jsFiddle.

Upvotes: 1

seyed
seyed

Reputation: 2055

you must add negative margin. and some other div. for example change your code to:

html:

<div class="image">
  <div class="image-container">
    <img src="http://lorempixum.com/80/80">
  </div>
  <div class="sharerDiv">
  <p>Hello!</p>

    </div>

</div>

css:

.sharerDiv{
  display:none;
}
.image-container{
  width: 80px;
  height: 80px;
}
.image-container:hover + .sharerDiv{
  display:block;
  margin-top: -49px;
}
.image-container:hover img{
  visibility: hidden;
}

Upvotes: 0

Anthony Forloney
Anthony Forloney

Reputation: 91776

You can apply a parent container and add pseudo selector :hover to modify it's children like so,

HTML

<div id="social">
  <div class="image">
    <img src="http://lorempixum.com/80/80" />
        <div class="sharerDiv">
        <p>Hello!</p>
        </div>
  </div>
</div>

CSS

#social {
  width: 100px;
  height: 200px;
}

#social:hover img {
  display: none;
}

#social:hover .sharerDiv {
  display: block;
}

Now when you hover over the div#social it will remove the img from view and display only the text.

Update

I had applied the same type of parent element to your Case 1 with the same CSS below and it appears to work as expected. Here is my jsfiddle: http://jsfiddle.net/dxwma/18/

Upvotes: 3

Related Questions