White Knight White Knight - 1 year ago 55
CSS Question

How can i set png icon collection with CSS?

I have seen in many examples and jquery plugins and CSS styled htmlElements
that they set icons of an image with several icons.

I want to do that practice with my apps.

icons array PNG

for example in that image, how can I choose one in CSS? or what is the correct way to choose one of them??

Any examples?

thank you!

Answer Source

The trick with CSS here is that you are displaying the whole image, but it's translated, and clipped by its parent, either by setting it as a background or as an image that is absolute positioned and overflow: hidden.

For example, let's assume the following HTML:

<div class="sprite-images checkbox"></div>

And let's assume that the checkbox we want to show is at (32, 32) in the spritesheet, and is 32x32px in size.

Then, your CSS would look something like this:

    width: 32px;
    height: 32px;
    display: block; // this doesn't matter too much, but can't be inline

    background-image: url("images/my_spritesheet.png"); // <-- insert spritesheet url
    background-position: 32px 32px; // <-- these are the spritesheet coords for the actual icon

And it's as simple as that. That background-image will automatically be clipped by the div itself, which we've already set to the sprite size of 32x32, so it's just a matter of translating it in the background so only the sprite you want is visible.