You can position a <div>
element at specific coordinates using JavaScript by dynamically setting its style.left
and style.top
properties.
For example, we write:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Positioning a DIV with JavaScript</title>
<style>
#myDiv {
width: 100px;
height: 100px;
background-color: red;
position: absolute; /* Important for positioning */
}
</style>
</head>
<body>
<div id="myDiv"></div>
<script>
// Get the reference to the div
var div = document.getElementById('myDiv');
// Set the position
div.style.left = '100px'; // X-coordinate
div.style.top = '50px'; // Y-coordinate
</script>
</body>
</html>
In this example, the #myDiv
is positioned absolutely within its nearest positioned ancestor (or the <body>
if there’s none).
The JavaScript part dynamically sets its left
and top
styles to position it at (100px, 50px)
.
You can adjust these coordinates as needed.
Remember, the positioning is relative to the nearest positioned ancestor.
If you want to position it relative to the viewport, you can use position: fixed
instead of absolute
.