How to convert CSS background-position property from percent to pixels?

I am now centering the background (using background-position: 50% 50%; ), which I would like to animate with Javascript. But, I want to be able to animate this using pixel measurements. In fact, I want to set the background position to something like "50% + 10px". Is it possible to use Javascript?

I can do this by finding the height of the background image and the height of the browser screen and doing some arithmetic, but this seems like a confusing solution.

+4
source share
1 answer

In the future, this will be possible with the CSS3 calc function. But since this is not widely supported now, below is a more practical solution.

Just use incremental notation jQuery supports for these properties. for instance

 $(some-element).css({ "background-position": "+=10px" }); 

This syntax was supported by $ .animate before it was supported by $ .css, but recent versions of jQuery support it in both cases.

Here jsfiddle demonstrates it in action .

+3
source

All Articles