CSS background image in :after element

落爺英雄遲暮 提交于 2019-12-18 12:49:29

问题


I'm trying to create a CSS button and add an icon to it using :after, but the image never shows up. If I replace the 'background' property with 'background-color:red' then a red box appears so I'm not sure what's wrong here.

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.

Thanks for any tips.


回答1:


A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.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;
}

I updated your jsFiddle to this and it showed the image.




回答2:


As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

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

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.



来源:https://stackoverflow.com/questions/14695365/css-background-image-in-after-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!