align div in center vertically in javascript

To align a div in center vertically using javascript, you can use the following code:

<div id="myDiv"></div>
23 chars
2 lines
index.tsx
var div = document.getElementById('myDiv');
div.style.position = 'relative';
div.style.top = '50%';
div.style.transform = 'translateY(-50%)';
142 chars
5 lines

In the above code, we first get the div using its ID and then set its position to 'relative'. Then set the top property to '50%', which moves the div down by 50% of its container height. Finally, we use the transform property to move it back up by half of its own height (which centers it vertically).

Note that this will only work if the parent container has a defined height.

gistlibby LogSnag