CSS show div on hover

By , last updated October 5, 2019

Css is not always easy. In this article I will explain how to show elements while hovering over a link. There are several ways to do it: by toggling a display element and by changing an opacity.

HTML setup

We are going to set up a simple HTML list with ul and two li elements. We will also have an image thumbnail in each list element and a div element with an image title.

<ul class="row" id="thumbnails"> 
    <li> 
        <a href="#"> 
            <div class="thumbnail"> 
                <img width="240" height="240" src="" /> 
            </div> 
        </a>
        <div class="caption">
            Image overlay
        </div>  
    </li> 
</ul>

What we want to achieve is a slightly transparent overlay with a caption over the image when we hover over it:

css show div on link hover in list example

This effect can be achieved with CSS only.

Let’s prepare our images. We are going to position them near each other with a full covered link over. No default list bullets should be seen.

ul li a {
    display: block;
}
ul.row li {
    float: left;
    position: relative;
    margin: 0 0 20px 20px;
    overflow: hidden;
}
ul.row li .thumbnail {
    position: relative;
    width: 240px;
    height: 240px;
    overflow: hidden;
}
ul.row li a {
    width: 240px;
    height: 240px;
}

Next step is to style the caption. It will have a white font color on a darker transparent background:

ul.row li .caption {
    position: absolute;
    background-color: rgba(0, 0, 0, .5);
    top: 0;
    left: 0;
    width: 240px;
    height: 240px;
    overflow: hidden;
}
ul.row li .caption a{
    color: #FFF;  
}

We will cover two ways to show a caption when the mouse is over the image.

CSS with display

An easy way to show the caption as an overlay is to switch the display option from none to block. First, we set the default setting of a caption to display:none;.

ul.row li .caption {
   display:none;
}

On mouse over the image we will switch the display to block:

ul.row li:hover .caption {
    display:block;
}

That’s it! The caption will then come up over the image with the mouse on hover.

CSS with opacity

Changing opacity is a more beautiful way to show the information overlay. With opacity you can set a transition time from no opacity to fully visible caption. This will give a more professional and soft look of your web page.

To use an opacity option give the original caption no opacity at all:

ul.row li .caption {
    opacity: 0;
}

Now we will gradually increase the opacity level to 1 (that is a maximum) of our caption on mouse over:

ul.row li:hover .caption {
    opacity: 1;
    transition: opacity 0.2s linear 0s;
}

That’s it!

See the example code at jsfiddle.