DEV Community

Bruno Bernard
Bruno Bernard

Posted on

How to center a div ? Seriously!

Well, glad you asked !

.center {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

or tailwind way !

<div class="h-screen flex justify-center items-center">
  One does not simply center a div
</div>
Enter fullscreen mode Exit fullscreen mode

Or make it even funky.

window.addEventListener('resize', centerDiv);
document.addEventListener('DOMContentLoaded', centerDiv);
function centerDiv() {
   let container = document.querySelector('.center');
   let windowHeight = window.innerHeight;
   let containerHeight = container.offsetHeight;
   let containerWidth = container.offsetWidth;

   // Calculate the position to center the div vertically
   var topPosition = (windowHeight - containerHeight) / 2;
   // Calculate the position to center the div horizontally
   var leftPosition = (containerWidth / 2);
   // Apply the margin to the div
   container.style.marginTop = topPosition + 'px';
   container.style.marginLeft = leftPosition + 'px';
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)