7

How can I centralize a Bootstrap V4 modal with CSS?

tao
  • 82,996
  • 16
  • 114
  • 150
wonderful world
  • 10,969
  • 20
  • 97
  • 194

2 Answers2

15

You can vertical center the modal by overriding the position of the .modal-dialog like this..

.modal.show .modal-dialog {
    -webkit-transform: translate(0,-50%);
    -o-transform: translate(0,-50%);
    transform: translate(0,-50%);
    top: 50%;
    margin: 0 auto;
}

http://www.codeply.com/go/14Ki1kyTgo

Update 2018

As of Bootstrap 4 Beta 3, there is a new modal-dialog-centered class that can be used instead of the custom method described above.

https://www.codeply.com/go/lpOtIFoN6E (Beta 3)

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • That is surely working. Can I ask why *translate(0,-50%);* is also needed? – wonderful world Feb 23 '17 at 12:42
  • It's a vertical centering [trick](http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/). It finds the center of the viewport (`top: 50%` & `transform: translateY(-50%)`) when the height of the element (modal) is unknown. – Carol Skelly Feb 23 '17 at 12:55
  • @wonderfulworld, note using this centering method on modals taller than the viewport causes the top part of the modal to become inaccessible. – tao Aug 24 '17 at 06:12
  • I don't know why but this fix doesn't work at chrome on Iphone 6+ – Evgenii Dec 11 '17 at 18:33
3

Using Flexbox its really easy to add vertical align bootstrap 4 modal popup. Here's the CSS Code.

See Woking Demo

SASS

.modal-open .modal.modal-center {
    display: flex!important;
    align-items: center!important;
    .modal-dialog {
        flex-grow: 1;
    }
}

Compiled CSS

.modal-open .modal.modal-center {
  display: -webkit-box !important;
  display: -ms-flexbox !important;
  display: flex !important;
  -webkit-box-align: center !important;
      -ms-flex-align: center !important;
          align-items: center !important;
}
.modal-open .modal.modal-center .modal-dialog {
  -webkit-box-flex: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
}

See Woking Demo

Surjith S M
  • 6,642
  • 2
  • 31
  • 50