center a div in javascript

To center a div in JavaScript, you can manipulate the left and top positions of the element using the window.innerWidth and window.innerHeight properties. Here's an example:

<div id="myDiv">Center me!</div>
33 chars
2 lines
#myDiv {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: yellow;
}
94 chars
7 lines
index.tsx
var myDiv = document.getElementById("myDiv");
var left = (window.innerWidth / 2) - (myDiv.offsetWidth / 2);
var top = (window.innerHeight / 2) - (myDiv.offsetHeight / 2);
myDiv.style.left = left + "px";
myDiv.style.top = top + "px";
233 chars
6 lines

In this example, we first get a reference to the div element using its id. We then calculate the left and top positions required to center the element by subtracting half of its width and height from half of the width and height of the screen respectively. Finally, we set the left and top positions of the element using the style property of the div.

gistlibby LogSnag