htmlcssbackground

CSS background image in :after element


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.

.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;
}
<a class="button green"> Click me </a>

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

Thanks for any tips.


Solution

  • 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.