on hover overlay image in CSS

狂风中的少年 提交于 2019-12-18 05:21:21

问题


I need a div with picture bg to overlay an image (with some amount transparency) when hovered on. I need to be able to have one transparent overlay that can be used and reused throughout the site on any image. My first attempt was round-about to say the least. Because I found out you cannot roll-over an invisible div I devised a sandwhich system in which the original image is the first layer, the overlay is the second layer, and the original image is third layer again. This way, when you roll-over, the original image disappears revealing the overlay image over the original image:

http://www.nightlylabs.com/uploads/test.html

So it works. Kinda. Because of you cannot interact with an visibility:invisible element (why?!) the roll-over flickers unless you rest the cursor on it.

Any help? This method is bad so if anyone has a better one please comment.


回答1:


I used the following css and its fine.

#container { position:relative; width:184px; height:219px;}
    .image { background-image:url(alig.jpg); position:absolute; top:0; left:0; width:184px; height:219px; z-index:2;}
    .overlay { background-image:url(aligo.png); position:absolute; top:0; left:0; width:184px; height:219px; z-index:3;}
    .top-image { background-image:url(alig.jpg); position:absolute; top:0; left:0; width:184px; height:219px; z-index:4;}
    .top-image:hover { background-image:none;}



回答2:


The image flickers because you can't hover over something that isn't there. It will work if you have it layered normally (no z-index necessary) and make it transparent, so that it is still being displayed and can be hovered over. The second image won't flicker, and you can control the styling with the span tag. Here's some of the CSS I used:

img.side
    {position:absolute;
    border:1px solid black;
    padding:5px 5px 5px 5px;
    float:center;}
    /*normal base images*/

img:hover+span
        {display:block;}
    /*new images. automatically display beneath base/hover image*/

.side:hover
        {opacity:0;}
    /*base images again, only when hovered over*/

span
        {display:none;
        cursor:pointer;}

The hover tag determines the styling of the base img (and base div), and hover+span defines the styling of the img that only appears when hovering.

Here is the html showing the div entirely:

    <div class="only" id="one">
            <img class="side" id="ach" src="ach.svg">Academic</a>
                <span>
                <img class="hovering" id="hach" src="Hach.svg">Academic</a>
                </span>
        </div>

Hope this helps.



来源:https://stackoverflow.com/questions/2474198/on-hover-overlay-image-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!