1

I have some divs that appear when you hover an image. However, I want to have a transition rather than the images appearing so abruptly. I'm trying to avoid javascript if possible.

img {
display: none
}
p.one:hover + img {
display: block;
}
p.two:hover img {
display: block;
}

http://jsfiddle.net/nmeyf03r/56/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
user2252219
  • 835
  • 3
  • 17
  • 41
  • You can't do transitions on the `display` property. Try the answer in [this question](http://stackoverflow.com/questions/3331353/transitions-on-the-display-property) instead. – BrokenBinary Aug 29 '15 at 02:15
  • Like @BrokenBinary has said, transitions won't work with `display: none`. However, you can use other CSS properties to get the effect you want. See my answer below. – Michael Benjamin Aug 29 '15 at 04:21

1 Answers1

1

Transitions don't work with display: none. You can't fade in an element that's been removed from the page. Similarly, you can't fade out a display: block element. With display, the element is either in or out.

However, you can still transition your divs with CSS using the visibility, opacity and height properties.

HTML

<p class="one">HOVER OVER ME - IMG IS SIBLING</p>
     <img src="http://www.placecage.com/100/100">
<p class="two">HOVER OVER ME -IMG IS CHILD</p>
    <img src="http://www.placecage.com/100/100">

CSS

img {
    visibility: hidden;
    opacity: 0;
    height: 0;
    transition: height .5s linear, opacity .5s linear;
}

p.one:hover + img {
    visibility: visible;
    opacity: 1;
    height: 100px;
    transition-delay: 0s;
}

p.two:hover + img {
    visibility: visible;
    opacity: 1;
    height: 100px;
    transition-delay: 0s;
}

Here's your demo, updated with the code above:
http://jsfiddle.net/nmeyf03r/58/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    Exactly - even if display were animatable, the browser wouldn't know how exactly the author *wants* the transition to look. That's why you have to tell it specifically to fade out the element, or shrink its width/height, or whatever. – BoltClock Aug 29 '15 at 05:32