Bruno Bernard
Posted on January 16, 2024
Well, glad you asked !
.center {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
or tailwind way !
<div class="h-screen flex justify-center items-center">
One does not simply center a div
</div>
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';
}
💖 💪 🙅 🚩
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
webdev Your Web Dev Is Actually a Distributed Systems Wizard (And They Don't Even Know It)
October 23, 2024