Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to position a div at specific coordinates ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given an HTML document, The task is to position an <div> at specific coordinates on the web page using JavaScript. we’re going to discuss a few techniques. 

Approach:

Example 1: In this example, the DIV is positioned at the end of the document. 

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP" style="font-size: 19px;
            font-weight: bold;">
</p>
<div id="GFG_DIV">
    This is Div box.
</div>
<br>
<button onClick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN" style="color: green;
            font-size: 24px;
            font-weight: bold;">
</p>
<script>
    var el_up =
        document.getElementById(
        "GFG_UP");
    var el_down =
        document.getElementById(
        "GFG_DOWN");
    el_up.innerHTML =
    "Click on button to change"+
    " the position of the DIV.";
      
    function GFG_Fun() {
        var x = 370;
        var y = 250;
        var el = document.getElementById('GFG_DIV');
        el.style.position = "absolute";
        el.style.left = x + 'px';
        el.style.top = y + 'px';
        el_down.innerHTML =
        "Position of element is changed.";
    }
</script>

Output:

Position a div at specific coordinates

Position a div at specific coordinates

Example 2: In this example, the DIV is positioned at the top-left corner of the document. 

html




<style>
    #GFG_DIV {
        background: green;
        height: 50px;
        width: 80px;
        margin: 0 auto;
        color: white;
    }
</style>
id="body">
<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP" style="font-size: 19px;
            font-weight: bold;">
</p>
<div id="GFG_DIV">
    This is Div box.
</div>
<br>
<button onClick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN" style="color: green;
            font-size: 24px;
            font-weight: bold;">
</p>
<script>
    var el_up =
        document.getElementById("GFG_UP");
    var el_down =
        document.getElementById("GFG_DOWN");
    el_up.innerHTML =
    "Click on button to change the position of the DIV.";
      
    function GFG_Fun() {
        var x = 0;
        var y = 0;
        var el = document.getElementById('GFG_DIV');
        el.style.position = "absolute";
        el.style.left = x + 'px';
        el.style.top = y + 'px';
        el_down.innerHTML = "Position of element is changed.";
    }
</script>

Output:

Position a div at specific coordinates

Position a div at specific coordinates


My Personal Notes arrow_drop_up
Last Updated : 19 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials