How to position a div at specific coordinates ?
Last Updated :
20 Jun, 2023
Given an HTML document and the task is to set the position of a <div> at specific coordinates on the web page using JavaScript. we’re going to discuss a few techniques.
Approach:
Example 1: In this example, we will set the DIV at a specific position at the end of the document.
html
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to position a div at
specific coordinates?
</title>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on button to change
the position of the DIV
</h3>
<div id="GFG_DIV">
This is Div box.
</div>
<br>
<button onClick="GFG_Fun()">
click here
</button>
<h3 id="GFG" style="color: green;"></h3>
<script>
let elm = document.getElementById("GFG");
function GFG_Fun() {
let x = 370;
let y = 250;
let el = document.getElementById('GFG_DIV');
el.style.position = "absolute";
el.style.left = x + 'px';
el.style.top = y + 'px';
elm.innerHTML =
"Position of element is changed.";
}
</script>
</body>
</html>
|
Output:

Position a div at specific coordinates
Example 2: In this example, the DIV is positioned at the top-left corner of the document.
html
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to position a div at
specific coordinates?
</title>
<style>
#GFG_DIV {
background: green;
height: 50px;
width: 80px;
margin: 0 auto;
color: white;
}
</style>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on button to change
the position of the DIV.
</h3>
<div id="GFG_DIV">
This is Div box.
</div>
<br>
<button onClick="GFG_Fun()">
click here
</button>
<h3 id="GFG" style="color: green;"></h3>
<script>
let elm = document.getElementById("GFG");
function GFG_Fun() {
let x = 0;
let y = 0;
let el = document.getElementById('GFG_DIV');
el.style.position = "absolute";
el.style.left = x + 'px';
el.style.top = y + 'px';
elm.innerHTML = "Position of element is changed.";
}
</script>
</body>
</html>
|
Output:
Share your thoughts in the comments
Please Login to comment...