css fade in transition for block text when hovering image?

Superfast Goose picture Superfast Goose · Oct 21, 2013 · Viewed 20.2k times · Source

So this is my code and I was looking to use css3 transitions to fade in the text and background colour when you hover the image. I've tried numerous selectors and transition types but cant seem to get it right any help is greatly appreciated.

see demo below

http://jsfiddle.net/jiceb/xsFmA/

<a href="#">
      <h2>Some Text</h2>
      <img src="http://www.sheridanrogers.com.au/wp-content/uploads/2011/03/American-pancakes.jpg"/>
</a>

and css

a { position: relative; display: inline-block }

a img {
    width:250px;
}

a h2 {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: 0;
    background: black;
    color: #fff;
}

a:hover h2 {
    display: block;
}

Answer

James Donnelly picture James Donnelly · Oct 21, 2013

Rather than using display:none and display:block, simply use opacity and add a transition to your a h2 selector:

a h2 {
    opacity:0; /* Completely invisible. */
    transition:1s; /* A 1 second transition. */
}

a:hover h2 {
    opacity:1; /* Completely visible. */
}

This will cause the opacity to increase from 0 to 1 over the period of 1 second.

JSFiddle demo.