user2826499 user2826499 - 4 months ago 8
HTML Question

Change Image Color in Button

I'm having trouble in changing the image color inside of a button.

Here's the image.

enter image description here

I want the black download button icon change to green icon if possible in CSS? or any other way to make it like that? Instead of re-creating it again

And for the code:

<button><em class="leftImage"></em>Button<em class='rightImage'></em></button>


button{
margin: 0px;
padding: 0px;
font-family:Lucida Sans MS, Tahoma;
font-size: 12px;
color: #000;
white-space:nowrap;
width:auto;
overflow:visible;
height:28px;
}

button em{
vertical-align:middle;
margin:0 2px;
display:inline-block;
width:16px;
height:16px;
background-image: url(icon_delete.png);
}

button em.leftImage{
background-position: -96px -112px;
}

button em.rightImage{
background-position: -64px -16px;

}


But the output is not changing the color. its still black.
https://jsfiddle.net/35kfu6z7/

Answer

You original code doesn't make much sense.

What you have here is an image with the 2 versions of your button. You can use a technique called CSS Sprites: https://css-tricks.com/css-sprites/

The idea here is to force the size of the button element to be the same size as the button on your image, then offset it using the background-position property to align it properly inside your button.

Here is an example using the picture you provided and 2 different clases (with 2 different offset) to show either the green or the black:

button{
    display:inline-block;
    width:84px;
    height:26px;
    
    background-image: url(http://i.stack.imgur.com/8aNAf.png);
    background-color: none;
    border: none;
}

button.green{
    background-position: -3px 31px;
}

button.black{
    background-position: -3px -3px;
}
<button class="green"></button>
<button class="black"></button>