Steven
Steven

Reputation: 18859

Using one background image position to toggle images

So I have a list item with a background image. When a user hovers over the list item, I want the background item to change. I'm using this:

li       { width: 400px; height: 80px;
           background-repeat: no-repeat; background-position: 10px 10px;
           background-image: url('myimg.png'); }
li:hover { background-image: url('myimg-hover.png'); }

Unfortunately this causes a bit of a flicker the first time you view the page and hover over an item.

I'd rather combine the images into one image, and just change the background image position when you hover over the list item.

The images combined into one is 25px wide and 50px tall, with the image displayed being only 25px x 25px.

I tried this:

li       { background: url('mynewimg.png') 0 0; }
li:hover { background: url('mynewimg.png') 0 -25px; }

But that just shows the entire image since my list item is so large, and doesn't position it right.

Anyone know how I can do this?

Upvotes: 0

Views: 96

Answers (3)

vals
vals

Reputation: 64174

Your CSS should be:

li {
    width: 400px; height: 80px;
    background-repeat: no-repeat;
    background-size: 50px 50px; 
    background-position: 10px 10px;
    background-image: url('mynewim.png'); 
    background-origin: 0px 0px;
}
li:hover { 
   background-origin: 50px 0px; 
}

You have to set the size explicity, and then play with origin

Upvotes: 1

Arpit Srivastava
Arpit Srivastava

Reputation: 2235

What I can do like :

<li class="icon"><i></i></li>

.icon {
  width:25px;
  height:50px;
  display:table-cell;
 vertical-alignment:middle;
}
.icon>i
{
  background:url();
  background-position:<value>px,<value>px
}
.icon:hover>i{
background-position: <value>px,<value>px
}

Hope this solution solves your problem.

Upvotes: 2

user2578173
user2578173

Reputation:

Without jsFiddle I can't visualize the example, but I think you are talking about image sprites. Check out http://css-tricks.com/css-sprites/ for more information about them.

Upvotes: 0

Related Questions