Categories
JavaScript Answers

How to position a div in a specific coordinates with JavaScript?

Spread the love

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

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

How to position a div in a specific coordinates with JavaScript?

To position a div in a specific coordinates with JavaScript, we can set the position, left and top styles.

For instance, we write

const d = document.getElementById("yourDivId");
d.style.position = "absolute";
d.style.left = xPos + "px";
d.style.top = yPos + "px";

to select the div with getElementById.

Then we set the position CSS property to 'absolute'.

And then we set the left and top styles to xPos and yPos respectively.

They’re both in pixels.

Conclusion

To position a div in a specific coordinates with JavaScript, we can set the position, left and top styles.

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 *