-->

how do i use css sprites

2019-09-06 20:29发布

问题:

I have a sprite that I want to use defining a class to and not an id:

I want to use the white one to show expansion option and black one to show expanded state. For non expanded state I have a class sprite-right and want to use sprite-expanded for expanded state. Can anyone guide me through this? I forgot pasting what I did...duh!

sprite-right
{
    overflow:hidden;
    width:16px;
    height:20px;
    cursor:pointer;
    background:transparent no-repeat 0 0;
    background-image:url('../images/arrows.gif');
}

回答1:

It's pretty simple to set up. You first need to set a class for applying the image as a background. Then add specific classes for each icon. Then in your CSS you change the background position, height and width to match the location of each icon. Here is an example:

.icon {
    background-image: url('path/to/image.png');
    display: block;
}

.icon.sprite-right {
    background-position: 0 0;
    height: 10px; // You can change these for each sprite
    width: 10px; // You can change these for each sprite
}
.icon.sprite-expanded {
    background-position: -10px 0; 
}
.icon.sprite-right:hover  {
    background-position: -20px 0;
}
.icon.sprite-expanded:hover {
    background-position: -30px 0;
}

Then, as you add new sprites you simply adjust the position until you can see the icon and then adjust the height and width until you are not clipping the image.



回答2:

There are many great tutorials out there if you do a Google search. I use this tool alot when dealing with simple sprites.

Check out this link: http://labs.engageinteractive.co.uk/nav-o-matic/

Here is a codepen I forked so I can understand sprites a little better.

http://codepen.io/daugaard47/pen/lntzE

Study the code and it will start making sense to you. Use background positioning to move your sprites to the desired class/state.

Hope this helps a little.



回答3:

This post should help : http://mindthesemicolon.com/using-css-sprites/ It explains how to create and use sprites, with a code pen example.