HTML DOM Style backgroundPosition Property


The backgroundPosition property is used for setting or getting the initial position for the background image of an element relative to the origin.

Syntax

Following is the syntax for −

Setting the backgroundPosition property −

object.style.backgroundPosition = value

Values

Following are the values −

ValueDescription
top left
top center
top right
center left
center center
center right
bottom left
bottom center
bottom right
The positioning can be understood by their name. If you write only one value then the other will always be center.
xpos yposTo indicate the horizontal(x) and vertical position(y). It starts from top left corner with 0,0. Pixels are preferred as units although you can use any other CSS unit too.
x% y%To specify the positioning in horizontal(x) and vertical(y) position in terms of percentage. It starts from top left with 0% 0% and with bottom right cornet 100% 100%. Since specifying one value means the other will be center i.e. it will be at 50%.
initialFor setting this property to initial value.
inheritTo inherit the parent property value.

Example

Let us look at an example for the backgroundPosition Property −

<!DOCTYPE html>
<html>
<head>
<style>
   body{
      background-image: url("https://www.tutorialspoint.com/power_bi/images/power-bi-minilogo.jpg");
      background-repeat: no-repeat;
      background-attachment: fixed;
      background-position: 20% 60%;
   }
</style>
<script>
   function changeBackPosition(){
      document.body.style.backgroundPosition="top right";
      document.getElementById("Sample").innerHTML="The background image position is now changed";
   }
</script>
</head>
<body>
<h2>Learning is fun</h2>
<p>Free learning tutorial for all...</p>
<p>Change the background image position by clicking the below button.</p>
<button onclick="changeBackPosition()">CHANGE POSITION</button>
<p id="Sample"></p>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE POSITION button −

Updated on: 20-Aug-2019

28 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements