无法在html和css中创建一个按钮

时间:2012-09-19 16:58:42

标签: html css xhtml

我从制作按钮的简单方法开始。

<div id="button">
<a href="#"><img src="button.png"></a>
</div>

之后,只要有人将鼠标悬停在按钮上,图像就会发生变化,但事实并非如此,相关的css是

#button a:hover
{
    background-image: url('button2.png');
}

这里有什么问题?为什么按钮上的图像不会因鼠标悬停而改变。

2 个答案:

答案 0 :(得分:2)

如果你想这样做,你必须首先设置背景图像。您正在构建的按钮实际上包含实际的image标记,而不是背景图像。

所以可以解决这个问题:将button.png设置为按钮的背景图像,如下所示:

#button a
{
    background-image: url('button.png');
    height: 20px; /* set to actual height of button image */
    width: 200px; /* set to actual width of button image */
}

然后对于悬停状态执行:

#button a:hover
{
    background-image: url('button2.png');
}

不要忘记设置#button a的高度和宽度(将其设置为图像的尺寸),否则不会显示。

答案 1 :(得分:1)

您必须将代码更改为:

<div id="button">
<a href="#">&nbsp;</a>
</div>

而且,在CSS中:

#button
{
    width: /* image width goes here */px;
    height: /* image heightgoes here */px;
}
#button a
{
    display:block;
    background-image: url('button.png');
    text-decoration:none;
}
#button a:hover
{
    background-image: url('button2.png');
}

出于搜索引擎优化的目的,您还可以在<a>内写一个文本,例如:

<div id="button">
<a href="#">Title of the link</a>
</div>

然后以这种方式隐藏它:

#button
{
    overflow:hidden;
    text-indent:-999px;
    width: /* image width goes here */px;
    height: /* image heightgoes here */px;
}

或者这样:

#button
{
    overflow:hidden;
    width: /* image width goes here */px;
    height: /* image heightgoes here */px;
}
#button a
{
    ...other rules
    padding-left:/* a value higher than #button width */px;
}