Categories
JavaScript Answers

How to Position a Div in a Specific Coordinate with JavaScript?

Spread the love

We can set the style.top and style.left properties to position a div in a specific coordinate with JavaScript.

For instance, we can write:

<div>  
  hello world  
</div>

Then we can set the position of the div by writing:

const d = document.querySelector('div');  
d.style.position = "absolute";  
d.style.left = '10px';  
d.style.top = '20px';

We get the div with document.querySelector .

Then we set its position CSS property to 'absolute' with:

d.style.position = "absolute";

Then we set the left and top CSS properties with:

d.style.left = '10px';  
d.style.top = '20px';

The unit must be specified for left and top.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *