29

我正在尝试创建一个 CSS 按钮并使用 :after 向其添加一个图标,但图像从未出现。如果我用 'background-color:red' 替换 'background' 属性,则会出现一个红色框,所以我不确定这里有什么问题。

HTML:

<a class="button green"> Click me </a>

CSS:

.button {
padding: 15px 50px 15px 15px;
color: #fff;
text-decoration: none;
display: inline-block;
position: relative;
}

.button:after {
content: "";
width: 30px;
height: 30px;
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px no-scroll;
background-color: red;
top: 10px;
right: 5px;
position: absolute;
display: inline-block;
}

.green {
background-color: #8ce267;
}

你可以检查这个小提琴,看看我的意思。

感谢您的任何提示。

4

2 回答 2

57

几件事

(a) 你不能同时拥有背景颜色和背景,背景总是会赢。在下面的示例中,我通过速记将它们组合在一起,但这只会在图像不显示时产生颜色作为后备方法。

(b) no-scroll 不起作用,我认为它不是背景图像的有效属性。尝试类似固定的东西:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

我将您的jsFiddle更新为此并显示了图像。

于 2013-02-04T20:50:31.573 回答
6

正如 AlienWebGuy 所说,您可以使用背景图像。我建议您使用背景,但在 URL 之后还需要三个属性:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

解释:这两个零是图像的x和y定位;如果您想调整背景图像的显示位置,请使用这些(您可以使用正值和负值,例如:1px 或 -1px)。

不重复表示您不希望图像在整个背景中重复。这也可以是重复-x 和重复-y。

于 2013-02-04T20:55:35.720 回答