使用css在导航栏链接中插入背景图像

时间:2016-10-20 05:35:56

标签: html css html5 image css3

由于某些原因,如果我向css添加边框或其显示的任何样式但图像不是图像,则图像不会出现在导航栏中。如果我使用<img/>标记在html中明确添加图片,则会显示该图片,但hover结束将不起作用..

CSS

<style>
     nav{
        background-color: #FFFFFF;
        height:35px;
        text-align:center;
        border-top:1px solid #464140;
        border-bottom:1px solid #464140;
        padding-top:3px;
    }

    .img1{
        border-radius:4px;
        width:100%;
        height:100%;
        background-image: url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcR_a-PcgaUqYBJgn0JywzAQot-30Hl4tyODvxTj4F91pTbWE7fZ');
     }

     .img1:hover{
        border-radius:4px;
        background-image:url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTbV-LxTpyrvTdSdHF5ulyzUJoe12f6nQr8Gn3hM3TjUfZNiEc');
     }
</style>

HTML

 <body>
     <nav> 
         <a  href = "index.html" class = "img1" title = "HOME"> </a> 
     </nav>
 </body>

3 个答案:

答案 0 :(得分:3)

标签后面的标签是空的:

<a  href = "index.html" class = "img1" title = "HOME"> </a>

display:block;添加到您的img1类

答案 1 :(得分:3)

display: block添加到a代码中 - 默认情况下adisplay: inline,并且 0 {{1}如果内部没有内容,则 width

&#13;
&#13;
height
&#13;
nav {
  background-color: #FFFFFF;
  height: 35px;
  text-align: center;
  border-top: 1px solid #464140;
  border-bottom: 1px solid #464140;
  padding-top: 3px;
}
.img1 {
  border-radius: 4px;
  width: 100%;
  height: 100%;
  display: block;
}
.img1:hover {
  border-radius: 4px;
  background-image: url('http://placehold.it/200x200');
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

<强>样本:

http://plnkr.co/edit/UGuTJdmvDMCgLSmJ5PfZ?p=preview

适用于多个图片菜单:

http://plnkr.co/edit/IFuiYBVcGkERgMSOfsZO?p=preview

display:block属性添加到锚标记。锚标记默认是内联元素,因此没有宽度和高度。

&#13;
&#13;
 nav{
    background-color: #FFFFFF;
    height:35px;
    text-align:center;
    border-top:1px solid #464140;
    border-bottom:1px solid #464140;
    padding-top:3px;
}

.img1{
    border-radius:4px;
    width:100%;
    height:100%;
    background-image: url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcR_a-PcgaUqYBJgn0JywzAQot-30Hl4tyODvxTj4F91pTbWE7fZ');
    display: block;
 }

 .img1:hover{
    border-radius:4px;
    background-image:url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTbV-LxTpyrvTdSdHF5ulyzUJoe12f6nQr8Gn3hM3TjUfZNiEc');
 }





<!-- begin snippet: js hide: false console: true babel: false -->
&#13;
 <nav> 
     <a  href = "index.html" class = "img1" title = "HOME"> </a> 
 </nav>
&#13;
&#13;
&#13;