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.
Approach: The ::before pseudo selector places the background image before the selected element and if the selected element has a background color associated with it, we can use the z-index property to make the background image visible.
The most common & simple way to add background image is using the background image attribute inside the <body> tag. The background attribute which we specified in the <body> tag is not supported in HTML5.
The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.
::after (:after) In CSS, ::after creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With