Show a title when hovering over an image with jQuery or CSS

Posted February 5, 2014 in Web Development


Screenshot of hovering over a thumbnail
Looks kinda like that.

It’s not too hard! I was writing up a demo and figured I might as well share it with the world. You can do it in CSS or jQuery, definitely useful for galleries.

The Markup

A couple of figures surrounded by a nice, clearfixed wrapper (love those!):


<div class="wrapper clearfix">

    <figure class="gallery-item">
        <img src="http://placehold.it/300x300">
        <figcaption class="img-title">
            <h5>Image Title</h5>    
        </figcaption>
    </figure>

    <figure class="gallery-item">
        <img src="http://placehold.it/300x300">
        <figcaption class="img-title">
            <h5>Image Title</h5>    
        </figcaption>
    </figure>

</div>
       

The CSS

Style up a quick 50% grid and our image titles (they’ll be hidden). I’m assuming you already have a .clearfix style somewhere. To use CSS for the hide/show, uncomment the commented lines, and comment the display: none; on .img-title.


/* Uncomment everything commented to CSS for the hide/show */

.gallery {
    width: 25em;
    margin: 2em auto;
}

.gallery-item {
    height: auto;
    width: 48.618784527%;
    float: left;
    margin-bottom: 2em;
    position: relative;
}

    .gallery-item:first-child {
        margin-right: 2.762430939%;
    }

.gallery-item img {
    width: 100%;
}

.gallery-item:hover .img-title {
    /*opacity: 1;*/
}

.img-title {
    position: absolute;
    top: 0;
    margin: 0;
    height: 100%;
    width: 100%;
    text-align: center;
    /*opacity: 0;*/
    display: none; /* comment this out for CSS hover */
    background-color: #333;
    /*transition: all 0.5s ease;*/
}

    .img-title h5 {
        position: absolute;
        color: #fff;
        top: 33%;
        width: 100%;
        text-align: center;
    }


With jQuery

Here’s the hover function:


$(document).ready( function() {

    $('.gallery-item').hover( function() {
        $(this).find('.img-title').fadeIn(300);
    }, function() {
        $(this).find('.img-title').fadeOut(100);
    });
    
});

Done! Have fun with your copy pasta. And, if you are in NYC or thereabouts, the disgusting slush outside.