当鼠标悬停在链接上时如何显示图片 CSS

15

我正在使用这个可能简单的解决方案,但是我在stackoverflow或者互联网上没有找到与这个特定问题相关的帮助。

我有一个菜单,并且我想在你悬停在它上面时在链接下方或附近显示一张图片。我希望这可以在CSS中完成。这是我的代码。

HTML

<html>
    <head>
        <title></title>

        <link rel="stylesheet" type="text/css" href="startpage.css">


        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
     <div id="wrapper">


         <img id="baggrund" width="166" height="327" alt="back image" src="images/laerkeryg.jpg"/>
         <img id="cirkler" width="319" height="249" alt="circles" src="images/circles.PNG"/>
         <div id="header">/jacob gerlif pilegaard/</div>
         <div id="underheader">portfolio</div>   
          <ul>
            <li><a href="index.html">home</a></li>
            <li><a href="about.html">about</a></li>
            <li><a href="gallery.html">gallery</a></li>
            <li><a href="contact.html">contact</a></li>
            </ul> 
         </div>
     <img id="menucircle" width="50" height="50" alt="menu circle" src="images/circle.PNG"/>
          </body>
</html>

这是目前的CSS:

a:hover
{
    background-image: url('image/circle.PNG');
    background-repeat: no-repeat;
}

希望你们能帮助我!


在我看来,似乎运行良好?fiddle - Mr_Green
3个回答

35

处理这个问题的干净方法是使用:after伪元素

a:hover:after {
    content: url(image/circle.PNG); /* no need for qoutes */
    display: block;
}

即使在DOM中没有图像也可以。此外,请记住,图像的路径是相对于CSS文件而不是HTML文件的。

当然,图像将会推动锚点下方的内容。为了避免这种情况,您可以尝试:

a:hover {
    position: relative;
}
a:hover:after {
    content: url(image/circle.PNG); /* no need for qoutes */
    display: block;
    position: absolute;
    left: 123px; /* change this value to one that suits you */
    top: 56px; /* change this value to one that suits you */
}

@tnkh,你能解释一下这个例子在Firefox中哪一部分不起作用吗? - matewka

5
尝试将图像放在href中,并赋予样式"display: none"。
a:hover img{ display: block; }

那应该在鼠标悬停时显示图像。

1
这可能会导致SEO问题。给锚点设置固定高度将使其过时,并且更符合SEO标准。 - Markus Hofmann

1

对于背景图片,您需要为锚点设置宽度、高度(或相关的内边距),并将其显示为块级元素。

a:hover
{
    background-image: url('image/circle.PNG');
    background-repeat: no-repeat;
    background-position: center bottom;
    height:20px
    width:100px;
    display:block;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接