How to center a div ? Seriously!

eznix

Bruno Bernard

Posted on January 16, 2024

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
💖 💪 🙅 🚩
eznix
Bruno Bernard

Posted on January 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related