How to make in CSS an overlay over an image?

user984621 picture user984621 · Jan 13, 2014 · Viewed 224.2k times · Source

I am trying to achieve something like this:

this effect

When I hover over an image, I would like to put on that image this dark color with some text and the icon.

I am stuck here. I found some tutorials but they didn't work out for this case. Also, another issue -- every image has a different height. The width is always the same.

How can this effect be achieved?

Answer

dfsq picture dfsq · Jan 13, 2014

You can achieve this with this simple CSS/HTML:

.image-container {
    position: relative;
    width: 200px;
    height: 300px;
}
.image-container .after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    color: #FFF;
}
.image-container:hover .after {
    display: block;
    background: rgba(0, 0, 0, .6);
}

HTML

<div class="image-container">
    <img src="http://lorempixel.com/300/200" />
    <div class="after">This is some content</div>
</div>

Demo: http://jsfiddle.net/6Mt3Q/


UPD: Here is one nice final demo with some extra stylings.

.image-container {
    position: relative;
    display: inline-block;
}
.image-container img {display: block;}
.image-container .after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    color: #FFF;
}
.image-container:hover .after {
    display: block;
    background: rgba(0, 0, 0, .6);
}
.image-container .after .content {
    position: absolute;
    bottom: 0;
    font-family: Arial;
    text-align: center;
    width: 100%;
    box-sizing: border-box;
    padding: 5px;
}
.image-container .after .zoom {
    color: #DDD;
    font-size: 48px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -30px 0 0 -19px;
    height: 50px;
    width: 45px;
    cursor: pointer;
}
.image-container .after .zoom:hover {
    color: #FFF;
}
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"/>

<div class="image-container">
    <img src="http://lorempixel.com/300/180" />
    <div class="after">
        <span class="content">This is some content. It can be long and span several lines.</span>
        <span class="zoom">
            <i class="fa fa-search"></i>
        </span>
    </div>
</div>