To center a div horizontally and vertically in flexbox using JavaScript, you can use the following code:
69 chars4 lines
212 chars14 lines
index.tsx340 chars12 linesIn the CSS, we use display: flex on the container to enable flexbox. justify-content: center and align-items: center are used to center the child element horizontally and vertically respectively.
In the JavaScript, we first define the container and box elements using document.querySelector(). Then, we create a centerBox() function that calculates the height difference between the container and the box, and sets the marginTop CSS property of the box element accordingly.
Finally, we add an event listener for the resize event and call the centerBox() function initially to center the box on page load.
gistlibby LogSnag