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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay