Change the position of a background-image:
document.body.style.backgroundPosition = "top right";
<!DOCTYPE html> <html> <head> <style> body {/* ww w. java 2 s . c o m*/ background-image: url('background1.png'); background-repeat: no-repeat; } </style> </head> <body> <button type="button" onclick="myFunction()">Position background image</button> <script> function myFunction() { document.body.style.backgroundPosition="top right"; } </script> </body> </html>
The backgroundPosition property sets or gets the position of a background-image within an element.
Property Values
Value | Description |
---|---|
top left If you only specify one keyword, the other value will be "center". top center top right center left center center center right bottom left bottom center bottom right | |
x% y% | The x value indicates the horizontal position and the y value indicates the vertical position. The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50%. |
x-pos y-pos | The x value indicates the horizontal position and the y value indicates the vertical position. The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and units |
initial | Sets this property to its default value. |
inherit | Inherits this property from its parent element. |
The backgroundPosition property default Value:0% 0%
The backgroundPosition property returns a String representing the position of a background-image.