Search code examples
htmlcssmousehover

Overlaying color over an image


Can I add an overlaying color once someone hover over an image/div in this particular case? Right now I'm showing the image at 80% and once someone hovers over it it displays at 100% to create an effect. The image/background in question is part of a sprite:

<div class="main">
     <a class="thumb" style="background: url(image.png) -150px 0;" href="url"></a>
     <div class="title">
        <a href="url">Text</a>
     </div>
</div>

And the CSS:

.thumb {
    display: block;
    background-repeat:no-repeat;
    height: 75px;
    width: 150px;
    opacity:0.8;
    filter:alpha(opacity=80);
}
a.thumb:hover {
    opacity:1.0;
    filter:alpha(opacity=100);
}

Solution

  • You could use a pseudo class that takes up the height and width of your element and only shows up when the element is hovered.

    Use rgba() to give a translucent colour. Adjust the RGB values accordingly.

    Note the relative position I have given to .thumb, to ensure the pseudo element is absolutely positioned relative to its parent.

    .thumb {
        position:relative;
        display: block;
        background-repeat:no-repeat;
        height: 75px;
        width: 150px;
        opacity:0.8;
        filter:alpha(opacity=80);
        position:relative;
    }
    a.thumb:hover {
        opacity:1.0;
        filter:alpha(opacity=100);
    }
    a.thumb:hover:after {
        position:absolute;
        top:0;
        left:0;
        width:100%;
        height:100%;
        display:block;
        content:'';
        background:rgba(255, 0, 0, 0.3);
    }
    <div class="main">
        <a class="thumb" style="background: url(https://i.sstatic.net/KmG7H.png) -150px 0;" href="url"></a>
        <div class="title">
            <a href="url">Text</a>
        </div>
    </div>