Explain Codes LogoExplain Codes Logo

Vertically centering Bootstrap modal window

html
responsive-design
css
bootstrap
Nikita BarsukovbyNikita Barsukov·Mar 9, 2025
TLDR
.modal-dialog { display: flex; align-items: center; min-height: 100vh; margin: 0; }

Use flexbox on .modal-dialog by setting display: flex; and align-items: center; for vertical centering. I'm sure you can smell the flex appeal! Set min-height to 100vh for full screen coverage and margin to 0; because we all love to cut margins, don't we? Perfectly centered modal, even on scrolling pages.

Pulling back the curtain: Centering techniques

Deep-dive into how to charm your Bootstrap modal to the center stage of your viewport.

I'm here, right in the middle - Bootstrap's helper class

For Bootstrap 4+, use .modal-dialog-centered class. It's as if Bootstrap read your question and is saying, "Hey, I got you covered!"

<div class="modal-dialog modal-dialog-centered"> <!-- Modal content --> </div>

CSS to the rescue! Vertical alignment with our good old "helper-div"

Don't fancy flex magic? No worries, we've got you. Opt for CSS and a "helper-div". A tiny tweak for man, a huge effect for UX!

.helper-div { display: table; height: 100%; width: 100%; } .modal-dialog { display: table-cell; vertical-align: middle; pointer-events: none; /* Don't touch me! I might tickle. */ } .modal-content { pointer-events: auto; /* You can touch me all you want! */ margin: 0 auto; /* To my left, to my right, I find happiness in the middle */ }

Wrap your .modal-dialog in a div with .dialog-center-helper. Now, wasn't that smooth?

Responsive and sassy

Adapting to window resizing and different screen sizes? Modal's got style!

@media (min-width: 768px) { .modal-dialog { padding-top: 10%; /* "10%": Hakuna Matata (no worries), I'll take care of viewport height */ } }

Tip: Keep an eye on the modal height, so it doesn't take more space than viewport and cause an ugly scroll.

Flexin' in Bootstrap 5

Bootstrap 5? No problem! More flex (muscles) = more centering power

<div class="modal-dialog m-0 d-flex align-items-center min-vh-100"> <!-- Modal content --> </div>

Watch out for common cold-er, I mean issues!

Ironing out problems

Keep an eye out taller modals and pointer-events for the smoothest user experience, and dynamic content resizing.

Problem 1: Man, you're tall!

Taller than viewport modals? Adjust .modal-dialog's overflow-y to auto. The max-height warrior steps in to prevent the stretch and dreaded scroll.

Problem 2: Keep your hands off (pointer-events)

Enable pointer-events: auto; on .modal-content for smooth user interaction inside the modal. The helper-div with pointer-events: none; ensures users can click outside to close the modal.

Problem 3: I'm a chameleon (dynamic resizing)

Use JavaScript or jQuery to adjust the modal's position if content changes. But, make sure the modal is set to display: block; before it struts to the new position.