Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to position a div in a specific coordinate with JavaScript.

In this article, we’ll look at how to position a div in a specific coordinate with JavaScript.

Position a Div in a Specific Coordinate with JavaScript

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.

Conclusion

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

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 *