Change CSS styles for :hove state

Hi,

Quick question, I just want to clarify this with the experts.

If you are using an image as the background for something but you want a different image when hover, do you need to retype the background position if the image has the same size and is basically on the same position?

In other words if I have something like this as the background ….

#sample {
background-image:url(‘images/image.jpg’);
background-repeat:no-repeat;
background-position: top center;
}

but need a different image when hover do I just target the new image like this…

#sample:hover{
background-image:url(‘images/image-hover.jpg’);
}

Or do I need to position it as well, like this…

#sample:hover {
background-image:url(‘images/image-hover.jpg’);
background-repeat:no-repeat;
background-position: top center;
}

I tried it and it seams to work without reposition the second image but I just want to make sure this is ok to do.

In fact this is just an example a lot of times I only need to change the border for the :hover state and I’m always copying and pasting the code from the upstate, is this what should be done?

Thanks a lot.

Nope just shorthand like…

background:url(images/image.jpg) top center no-repeat;

And on hover

background:url(images/image2.jpg);

No, you don’t need to repeat anything that is specified in the general rule; it will automatically apply to :hover unless you overwrite it with a more specific rule.

Nope just shorthand like…

background:url(images/image.jpg) top center no-repeat;

And on hover

background:url(images/image2.jpg);

Would not work as expected.

The background: rule is a short hand notation…( you don’t actually need to use separate attributes to initially specify the bg of yoru element. Note also that :hover also adds a level of specificity to a rule ( .thisClass li is LESS specific than .thisClass li:hover).

background: REQUIRES AT LEAST the URI and sets it own default for attributes not specified. So if you do what Eric suggested, you will get a new bg image that repeats from the top left.

You can, however, set your original state using the background: shorthand and then use background-image: to change only the image for the hover:state.

example:

li{background:url(images/image.jpg) top center no-repeat;}
li:hover{background-image:url(images/image2.jpg) ;}

of course if you are changing many attributes at once then it would make sense to stick to “background:” shorthand

eg:

li{background:url(images/image.jpg) top center no-repeat;}
li:hover{background:url(images/image2.jpg) left bottom repeat-y #ccc;}

hope that helps

Thank you all for your help!