Richlewis
Richlewis

Reputation: 15374

Sprite image moves down when hovering over

I am using a sprite to change the color of an image on its hover status, though when I hover over the image it moves down slightly and changes color. I have created a JSFiddle to replicate the problem.

I am probably using the sprite incorrectly? I'm unsure as it is my first time playing with them.

.ratings ul li {
width:18px;
height:18px;
background:url(star.png) 145px 102px;
}

.ratings ul li:hover{
width:18px;
height:18px;
background:url(star.png) 145px 86px;
 }

I am using this image: enter image description here

Can anyone can point out my mistakes?

Upvotes: 1

Views: 1572

Answers (3)

Kev
Kev

Reputation: 5452

First: you should use a 16px "box" (width/height) for your star not 18 because your star has a width of 16px.

Then change your offset correctly, you will have less problem.

Upvotes: 2

Boaz
Boaz

Reputation: 20220

Cause

The sprite is not configured correctly. At least one of the background-position values should be either zero or negative in your example.

The technique of CSS sprites depends on negative background-position values to change the area within the image used as the element's background. In contrast, positive (i.e. greater than zero) background-position values actually change the position of the background image in the element.

Solution

background:url(star.png) 0 0;

background:url(star.png) 0 -18px;

See jsFiddle demo

Note about the image

Also note that your current sprite is 34px high, while it seems each star is only 16px high. This means there's a 2px gap between the two stars, so the second background-position is -18px and not -16px.

Upvotes: 4

agriboz
agriboz

Reputation: 4854

.ratings ul li {
  width:16px; /* redefine your image offset */
  height:16px; 
  background:url(https://i.sstatic.net/S5T0M.png) no-repeat;
}
.ratings ul li:hover {
  background-position: 0 -18px;
}

You do not need to define width and height which you had already on :hover state. You should find informative guidance about css sprires on this site

Upvotes: 3

Related Questions