Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to set the starting position of a background image in JavaScript DOM?
To set the starting position of a background image in JavaScript, use the backgroundPosition property. This property allows you to specify where the background image should be positioned within its container.
Syntax
element.style.backgroundPosition = "value";
Position Values
The backgroundPosition property accepts various values:
-
Keywords:
top,bottom,left,right,center -
Percentages:
50% 25%(horizontal vertical) -
Pixels:
10px 20px(horizontal vertical) -
Mixed:
left 50px,center top
Example: Setting Background Position
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-repeat: no-repeat;
background-size: 100px 100px;
height: 400px;
}
</style>
</head>
<body>
<button onclick="setTopRight()">Top Right</button>
<button onclick="setCenter()">Center</button>
<button onclick="setCustom()">Custom (50px 100px)</button>
<script>
// Set background image first
document.body.style.backgroundImage = "url('/html5/images/html5-mini-logo.jpg')";
function setTopRight() {
document.body.style.backgroundPosition = "top right";
}
function setCenter() {
document.body.style.backgroundPosition = "center";
}
function setCustom() {
document.body.style.backgroundPosition = "50px 100px";
}
</script>
</body>
</html>
Multiple Position Examples
<!DOCTYPE html>
<html>
<head>
<style>
.demo-box {
width: 300px;
height: 200px;
border: 2px solid #ccc;
margin: 10px;
background-repeat: no-repeat;
background-size: 50px 50px;
}
</style>
</head>
<body>
<div class="demo-box" id="box1"></div>
<div class="demo-box" id="box2"></div>
<div class="demo-box" id="box3"></div>
<script>
const boxes = document.querySelectorAll('.demo-box');
// Set background image for all boxes
boxes.forEach(box => {
box.style.backgroundImage = "url('/html5/images/html5-mini-logo.jpg')";
});
// Different positions
document.getElementById('box1').style.backgroundPosition = "left top";
document.getElementById('box2').style.backgroundPosition = "center";
document.getElementById('box3').style.backgroundPosition = "right bottom";
</script>
</body>
</html>
Position Values Reference
| Value | Description | Example |
|---|---|---|
top left |
Top-left corner | "0% 0%" |
center |
Center of element | "50% 50%" |
bottom right |
Bottom-right corner | "100% 100%" |
20px 30px |
Exact pixel position | 20px from left, 30px from top |
Conclusion
The backgroundPosition property provides flexible control over background image placement. Use keywords for simple positioning or precise values for exact control.
Advertisements
