【问题标题】:CSS background image in :after element:after 元素中的 CSS 背景图像
【发布时间】:2013-02-04 20:48:06
【问题描述】:

我正在尝试创建一个 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;
}

You can check this fiddle to see what I mean exactly.

感谢任何提示。

【问题讨论】:

    标签: css background


    【解决方案1】:

    几件事

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

    (b) 无滚动不起作用,我认为它不是背景图像的有效属性。尝试修复:

    .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 更新为此并显示了图像。

    【讨论】:

    • 看起来我搞砸了那里的背景值:) 感谢您的回复。
    • 我想添加一些在设置:after 元素样式时不太明显的内容:您必须设置content 的值在设置之前背景(图像),否则,它不会显示任何东西。如果您碰巧用空格以外的其他内容填充content 并将其放置在 背景(图像)之后,则将显示插入的值 背景图像.
    • 只是因为我很挑剔(:如果出于任何原因,您可以同时使用背景和背景颜色。后者将覆盖以前的例如 background:1px solid red;background-color:black ; === 背景:1px 纯黑色;
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 2018-06-29
      • 2018-04-23
      • 2011-05-04
      • 2013-03-05
      • 2014-06-30
      • 2015-06-18
      相关资源
      最近更新 更多