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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.