how to center a div in flexbox in javascript

To center a div horizontally and vertically in flexbox using JavaScript, you can use the following code:

<div class="container">
  <div class="box">Centered div</div>
</div>
69 chars
4 lines
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.box {
  width: 200px;
  height: 200px;
  background-color: yellow;
  text-align: center;
  line-height: 200px;
}
212 chars
14 lines
index.tsx
const container = document.querySelector('.container');
const box = document.querySelector('.box');

function centerBox() {
  const containerHeight = container.clientHeight;
  const boxHeight = box.clientHeight;
  box.style.marginTop = (containerHeight - boxHeight) / 2 + 'px';
}

window.addEventListener('resize', centerBox);
centerBox();
340 chars
12 lines

In 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.

related categories

gistlibby LogSnag