f w h

Easy CSS-only Image Description Hover

Look, Ma! No jQuery!

Recently, I was asked what jQuery plugin would be best for creating an overlay on an image that would show when the image is hovered. Truth be told, the effect is incredibly easy to accomplish using only CSS. This works in IE 8 and up, as well as Chrome and Firefox.

The HTML


<div class="img-wrap">
<img src="images/snowman.png" alt="" />
<div class="img-overlay">
<h4>Title</h4>
<p>A description of the image</p>
</div>
</div>

The HTML is fairly straightforward. The image and the text we want are wrapped in a div. The wrapper is used to contain everything and give the overlay a boundary to work with.

The CSS


.img-wrap{
height:314px;
overflow:hidden;
position:relative;
width:300px;
}
.img-overlay{
background-color:#000;
bottom:0;
color:#fff;
opacity:0;
filter: alpha(opacity = 0);
position:absolute;
width:100%;
z-index:1000;
}
.img-overlay h4, .img-overlay p{
padding:0 10px;
}
.img-wrap:hover .img-overlay{
opacity:0.75;
filter: alpha(opacity = 75);
transition:opacity 0.25s;
-moz-transition:opacity 0.25s;
-webkit-transition:opacity 0.25s;
}

The img-wrap class is set to the height and width of the image. That will keep the overlay contained to the width of the image. We’ll also set the position to relative so we can position the overlay within it. While it won’t necessarily help with a simple fade-in effect like we’re doing here, setting overflow:hidden; will keep things from bleeding over.

The img-overlay class positioning is set to absolute, and bottom offset to 0. That will peg the overlay to the bottom of the wrapper div. If you prefer the overlay show at the top, simply replace bottom with top. The opacity is set to 0 to hide the div. For Internet Explorer versions below 9, use the filter: alpha(opacity = 0);.

Making the Magic

The stage is set. Now for the simple hover effect. What we want to do is apply opacity to the overlay when the wrap is hovered. This is done using .img-wrap:hover .img-overlay. Now, apply your desired opacity level and a transition if desired.

That’s all there is to it! Other effects can be accomplished by playing with the positioning values. For instance, the overlay could be positioned off screen using a negative offset value, and then set to 0 for a slide-up effect.

See it in Action