289

This is a two part question:

  1. How can you position the modal vertically in the center when you don't know the exact height of the modal?

  2. Is it possible to have the modal centered and have overflow:auto in the modal-body, but only if the modal exceeds the screen height?

I have tried using this:

.modal-dialog {
  height: 80% !important;
  padding-top:10%;
}

.modal-content {
  height: 100% !important;
  overflow:visible;
}

.modal-body {
  height: 80%;
  overflow: auto;
}

This gives me the result I need when the content is much larger than vertical screen size, but for small modal contents it's pretty much unusable.

tronerta
  • 432
  • 6
  • 12
scooterlord
  • 15,124
  • 11
  • 49
  • 68

34 Answers34

395
.modal {
  text-align: center;
}

@media screen and (min-width: 768px) { 
  .modal:before {
    display: inline-block;
    vertical-align: middle;
    content: " ";
    height: 100%;
  }
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

And adjust a little bit .fade class to make sure it appears out of the top border of window, instead of center

Shankar Prakash G
  • 1,099
  • 18
  • 34
Finik
  • 3,967
  • 2
  • 11
  • 2
  • I was actually overriding this by mistake, thanks for pointing out out it actually works behind the scenes. – Dorian Nov 13 '14 at 17:36
  • This probably is the best way to center vertically not just the bootstrap modal but everything else. http://css-tricks.com/centering-in-the-unknown/ – Mark S Jan 20 '15 at 02:05
  • 4
    I clarify that this does not work very well on Mobile. Because the definition ":after" having a height of 100% and can automatically move the modal to down of the page. I just solved declaring .modal {display: flex! Important;} .modal-dialog {margin: auto}. The 92.97% of people already have support using this CSS property, however for general suporte can use JavaScript to set the margins. – Walter Chapilliquen - wZVanG Apr 04 '15 at 23:22
  • 23
    Absolutely great, but I would recommend using it only above 768px and leave default setting on mobile. Top position is best for modals when the screen height is small. I've also adjusted an animation to make it appear from the center, here the working example if anyone needs it: http://codepen.io/anon/pen/zGBpNq – bwitkowicz May 18 '15 at 14:28
  • This solution shift modal window to right for 2px, cause :before element. But this can be solved by add same code for :after – Cypher Oct 06 '15 at 05:41
  • It works like a charm. But could you elaborate more about why this setting work, as I'm new to css and layout. Especially why it needs `display: inline-block` – macemers Apr 26 '16 at 03:43
  • Such modal hides by fading (by default), but just before fading it jumps back from the centre to the left side, and only than fades. Pretty ugly... – Jānis Elmeris Oct 17 '17 at 19:36
155

1. How can you position the modal vertically in the center when you don't know the exact height of the modal?

To absolute center the Bootstrap 3 Modal without declaring a height, you will first need to overwrite the Bootstrap CSS by adding this to your style sheet:

.modal-dialog-center { /* Edited classname 10/03/2014 */
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
}

This will position the modal-dialogs top-left corner in the center of the window.

We have to add this media query or else the modal margin-left is wrong on small devices:

@media (max-width: 767px) {
  .modal-dialog-center { /* Edited classname 10/03/2014 */
    width: 100%;
  }
} 

Now we will need to adjust its position with JavaScript. To do that we give the element a negative top and left margin equal to half of its height and width. In this example we will be using jQuery since it is available with Bootstrap.

$('.modal').on('shown.bs.modal', function() {
    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return -($(this).outerHeight() / 2);
        },
        'margin-left': function () {
            return -($(this).outerWidth() / 2);
        }
    });
});

Update (01/10/2015):

Adding on Finik's answer. Credits to Centering in the Unknown.

.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px; /* Adjusts for spacing */
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

Notice the negative margin-right? This removes the space added by inline-block. That space causes the modal to jump to the bottom of the page @media width < 768px.

2. Is it possible to have the modal centered and have overflow:auto in the modal-body, but only if the modal exceeds the screen height?

This is possible by giving the modal-body an overflow-y:auto and a max-height. This takes a bit more work to get it working properly. Start with adding this to your style sheet:

.modal-body {
    overflow-y: auto;
}
.modal-footer {
    margin-top: 0;
}

We will use jQuery again to get the window height and set the max-height of the modal-content first. Then we have to set the max-height of the modal-body, by subtracting the modal-content with the modal-header and modal-footer:

$('.modal').on('shown.bs.modal', function() {
    var contentHeight = $(window).height() - 60;
    var headerHeight = $(this).find('.modal-header').outerHeight() || 2;
    var footerHeight = $(this).find('.modal-footer').outerHeight() || 2;

    $(this).find('.modal-content').css({
        'max-height': function () {
            return contentHeight;
        }
    });

    $(this).find('.modal-body').css({
        'max-height': function () {
            return (contentHeight - (headerHeight + footerHeight));
        }
    });

    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return -($(this).outerHeight() / 2);
        },
        'margin-left': function () {
            return -($(this).outerWidth() / 2);
        }
    });
});

You can find a working demo here with Bootstrap 3.0.3: http://cdpn.io/GwvrJ EDIT: I recommend using the updated version instead for a more responsive solution: http://cdpn.io/mKfCc

Update (30/11/2015):

function setModalMaxHeight(element) {
  this.$element     = $(element);  
  this.$content     = this.$element.find('.modal-content');
  var borderWidth   = this.$content.outerHeight() - this.$content.innerHeight();
  var dialogMargin  = $(window).width() < 768 ? 20 : 60;
  var contentHeight = $(window).height() - (dialogMargin + borderWidth);
  var headerHeight  = this.$element.find('.modal-header').outerHeight() || 0;
  var footerHeight  = this.$element.find('.modal-footer').outerHeight() || 0;
  var maxHeight     = contentHeight - (headerHeight + footerHeight);

  this.$content.css({
      'overflow': 'hidden'
  });

  this.$element
    .find('.modal-body').css({
      'max-height': maxHeight,
      'overflow-y': 'auto'
  });
}

$('.modal').on('show.bs.modal', function() {
  $(this).show();
  setModalMaxHeight(this);
});

$(window).resize(function() {
  if ($('.modal.in').length != 0) {
    setModalMaxHeight($('.modal.in'));
  }
});

(Updated 30/11/2015 http://cdpn.io/mKfCc with above edit)

Community
  • 1
  • 1
dimbslmh
  • 1,801
  • 1
  • 12
  • 8
  • 1
    excellent answer and post! However, can this also be animated? It works great when it just pops in, but what about animated? I am at work and can't test it atm, but I am eager to see the results – scooterlord Jan 24 '14 at 07:18
  • You can add a fade class on the modal. Check out my updated solution at http://cdpn.io/mKfCc – dimbslmh Jan 24 '14 at 16:58
  • Although it seems to be working great on codepen, I can't get it to work on my project. I guess you just need to add the code and not replace something right? – scooterlord Jan 24 '14 at 17:54
  • I tested your code in the stock theme and seems to be working fine (although it messes the code in my current project, I have to debug it), however resizing the screen with an open modal causes problems (even in your codepen snippet above). Once you correct this I will give this answer as positive! Great Job! :) – scooterlord Jan 24 '14 at 22:16
  • I have updated the JavaScript to work with an open modal. And yes, you have to add CSS to a style sheet other than the default bootstrap. Or else you will lose your customization when you update your bootstrap. – dimbslmh Jan 25 '14 at 10:41
  • Thanks again for your efforts, but it still isn't working properly. Although resizing works with an open modal, once you resize, close it and re-open it, it uses the original position as a vertical center. :/ – scooterlord Jan 25 '14 at 10:58
  • Ah, it should work now. Checking modal "in" state instead of the body.modal-open – dimbslmh Jan 25 '14 at 12:11
  • Well, I guess you deserve it then! :) – scooterlord Jan 25 '14 at 12:50
  • 1
    Hey again! Noticed the following. When the first modal first opens, the right margin is wrong until you resize once. Any ides on this one? – scooterlord Jan 31 '14 at 13:15
  • my bad, I was using overflow:hidden on .modal and the difference was the scrollbar width. – scooterlord Jan 31 '14 at 13:59
  • Sadly, this doesn't work if you make the screen small and then scroll within the window. Screenshot: http://take.ms/4m69x – Public Profile Mar 09 '14 at 05:26
  • Thanks for pointing that out Jon. This happens when the .modal-body max-height gets a negative value which is not valid. This will most likely occur on mobile devices with a very low resolution. It would be best to prevent the script from executing on those devices. I have done this by checking the initial window height. Updated my answer accordingly. – dimbslmh Mar 09 '14 at 20:28
  • @ambrus Can you reproduce this in a codepen/jsfiddle? I tried adding a img.img-responsive in a few modals, but I can't reproduce that bug. Perhaps you can try it again without my script. If it still occurs then you should report it to Bootstrap. – dimbslmh Mar 11 '14 at 09:39
  • You might would want to add `overflow:hidden` to remove annoying scroll bar! – Ilia Ross Jul 20 '14 at 20:24
  • I am using above solution , is there a way that modal is always at 100% height and if content exceed, modal-body should scroll as above. – django Aug 12 '14 at 13:58
  • I am having trouble getting this to work with remote modals. It seems the centering happens before the content is loaded in the modal. Once the content is loaded, the margin-top numbers are way off. Any solutions for this? – LBF Aug 22 '14 at 02:13
  • Does not work properly on Safari on iPad. The modal windows are vertically centered relative to the _whole_ page instead of only the display area. – bernie Sep 30 '16 at 18:58
  • @bernie can you tell me what Ipad generation, iOS & Safari version you tested this on? Seems like the CSS solution is failing on that specific device. – dimbslmh Oct 01 '16 at 22:15
  • @dimbslmh It's an iPad mini iOS 9.3.2. No idea how to get the safari version, but the user agent is `Mozilla/5.0 (iPad; CPU OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13F69 Safari/601.1` – bernie Oct 02 '16 at 16:06
  • 1
    @bernie I made screenshots on Browserstack with a fork of my codepen which has the short modal open on document.ready: https://www.browserstack.com/screenshots/6011a6b37b406484bf676490cb53764106b16461 Browserstack doesn't support v9.3.x for screenshots (yet), but I think something similar to what you described occurs on iOS 6.0 (See screenshot iPad 3rd (6.0)(Portrait)). Perhaps it's an old bug that has returned in v9.3.2. If you'd like to, you can file a bug report at https://forums.developer.apple.com/community/safari-and-web/ios-web-apps – dimbslmh Oct 03 '16 at 02:19
  • @dimbslmh Thanks for the follow-up! I opened a bug report here: https://forums.developer.apple.com/message/185166. – bernie Oct 03 '16 at 15:12
40

My solution

.modal-dialog-center {
    margin-top: 25%;
}

    <div id="waitForm" class="modal">
        <div class="modal-dialog modal-dialog-center">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 id="headerBlock" class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <span id="bodyBlock"></span>
                    <br/>
                    <p style="text-align: center">
                        <img src="@Url.Content("~/Content/images/progress-loader.gif")" alt="progress"/>
                    </p>   
                </div>
            </div>
        </div>
    </div>
Brian J. Hakim
  • 953
  • 12
  • 23
33

It can simply can be fixed with display: flex

.modal-dialog {
  margin-top: 0;
  margin-bottom: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.modal.fade .modal-dialog {
  transform: translate(0, -100%);
}

.modal.in .modal-dialog {
  transform: translate(0, 0);
}

With prefix

.modal-dialog {
  margin-top: 0;
  margin-bottom: 0;
  height: 100vh;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
      -ms-flex-pack: center;
          justify-content: center;
}

.modal.fade .modal-dialog {
  -webkit-transform: translate(0, -100%);
          transform: translate(0, -100%);
}
.modal.in .modal-dialog {
  -webkit-transform: translate(0, 0);
          transform: translate(0, 0);
}
Mo.
  • 26,306
  • 36
  • 159
  • 225
27

If you're okay with using flexbox then this should help solve it.

.modal-dialog {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
}

.modal-content {
  margin: 0 auto;
}
xiao
  • 1,718
  • 4
  • 23
  • 31
  • 8
    I find out this answer works great for me. However, if you want to let users close a modal by clicking it's backdrop, make sure to add `pointer-events: none` to `.modal-dialog` and `pointer-events: auto` to `.modal-content`. Becausu `.modal-dialog {height: 100%}` cover the whole column above and beneath a modal and disable users to click the backdrop on that area. – wuct Jun 23 '15 at 11:55
  • combined with suggestion from @ChingTingWu , most effective – strider Nov 24 '15 at 23:26
  • And where's @ChingTingWu suggestion? – giovannipds Aug 30 '16 at 17:03
  • 1
    ChingTingWu seems to have change to @wuct – xiao Aug 30 '16 at 19:14
  • 1
    @giovannipds Oops, I have renamed my username, because it's shorter and easier to be tagged. Sorry for confusing :) – wuct Aug 31 '16 at 02:08
  • @wuct, no problem, I guess it's just a site problem, it should be able to find / search and replace references. – giovannipds Oct 27 '16 at 08:53
  • Top of the content is cropped when the modal has scrollable content (more content than fits in the window) – Steven Pribilinskiy Jul 27 '18 at 09:46
25

I came up with a pure css solution! It's css3 though, which means ie8 or lower is not supported, but other than this it's tested and working on ios, android, ie9+, chrome, firefox, desktop safari..

I am using the following css:

.modal-dialog {
  position:absolute;
  top:50% !important;
  transform: translate(0, -50%) !important;
  -ms-transform: translate(0, -50%) !important;
  -webkit-transform: translate(0, -50%) !important;
  margin:auto 5%;
  width:90%;
  height:80%;
}
.modal-content {
  min-height:100%;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0; 
}
.modal-body {
  position:absolute;
  top:45px; /** height of header **/
  bottom:45px;  /** height of footer **/
  left:0;
  right:0;
  overflow-y:auto;
}
.modal-footer {
  position:absolute;
  bottom:0;
  left:0;
  right:0;
}

Here is a fiddle. http://codepen.io/anon/pen/Hiskj

..selecting this as the correct answer since there's no extra heavy javascript that brings the browser to its knees in case of more than one modals.

Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45
scooterlord
  • 15,124
  • 11
  • 49
  • 68
  • 9
    The whole point of using JavaScript was to get the **unknown** height of the modal. Your solution has a fixed height of 80%, which doesn't answer your own question: "How can you position the modal vertically in the center when you **don't know the exact height of the modal**?" – dimbslmh Apr 15 '14 at 08:48
  • 1
    ...the height dimension is set to limit the MAXIMUM modal height compared to the screen height. However, translate's percentage is set according to the CONTENT height. – scooterlord Apr 15 '14 at 11:19
  • 3
    If you want to get a solution that does not change the size of the modal box try the following css solution as well: http://tweaks.klickagent.ch/#30.05.2014_TwitterBootstrapCenterModal – klickagent.ch May 30 '14 at 14:13
  • Very nice as well. However, it has a different approach than the one I am describing. In your case the whole modal moves up and down, when in my case an overflown element is created. Very nice though! I like it! – scooterlord May 30 '14 at 22:04
  • This requires height to be set.. Which is not exactly the same as the user asks for. – rebellion Aug 14 '15 at 12:01
  • Very nice fiddle! I'm trying to find out how you managed to remove the whole footer area (which I'm trying to do in Rstudio / shiny app, but couldn't figure that out from your fiddle. Would be happy if you dropped a clue here :) – Mark Jul 26 '17 at 16:08
  • The modal footer is absolutely positioned, so either if it exists or not, it is out of the DOM flow. What is really important to you is the bottom value in pixels of the modal body, that leaves the necessary space for the modal to lie in. – scooterlord Jul 27 '17 at 06:39
25

My solution:

.modal.in .modal-dialog 
{
    -webkit-transform: translate(0, calc(50vh - 50%));
    -ms-transform: translate(0, 50vh) translate(0, -50%);
    -o-transform: translate(0, calc(50vh - 50%));
    transform: translate(0, 50vh) translate(0, -50%);
}
Vadim
  • 400
  • 4
  • 8
  • This seems to work perfectly with Bootstrap 3. Why isn't this the accepted answer? Its a lot simpler (4 css directives) than the others. – danielricecodes Dec 27 '17 at 01:16
  • @danielricecodes I'm going to take a shot and assume it's because of [the issues with viewport units.](https://caniuse.com/#feat=viewport-units). The proposed answer by scooterlord proposed compatibility even with IE9, and iOs, which suggest to me is a concern. If you check the issues page of canIuse, you will see that there are problems with iOs and IE10 and older. Not that I agree or not that this is the correct answer. I'm just pointing out why *maybe* this wasn't selected as the answer. – Malavos May 07 '18 at 14:30
  • 1
    There's an issue with this approach is when the modal has scrollable content (more content than fits in window) – Steven Pribilinskiy Jul 27 '18 at 09:32
  • This should be the accepted answer. So far this is the only solution works for me. Thanks for this. – shifu Sep 05 '18 at 06:29
  • This won't work if your modal content is greater than the screen height (if your modal has to scroll) – Brett Gregson Aug 30 '19 at 12:59
22

Adding this simple css also works.

.modal-dialog {
  height: 100vh !important;
  display: flex;
}

.modal-content {
  margin: auto !important;
  height: fit-content !important;
}
Ninja420
  • 3,542
  • 3
  • 22
  • 34
20

All what I did in my case is to set the Top in my css knowing the height of the modal

<div id="myModal" class="modal fade"> ... </div>

in my css i set

#myModal{
    height: 400px;
    top: calc(50% - 200px) !important;
}
Nerdroid
  • 13,398
  • 5
  • 58
  • 69
12

There is an easiest way to do this using css:

.modal-dialog {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    width:500px;
    height:300px;
}

That's it. Notice that it is only needed to be applied to the .modal-dialog container div.

Demo: https://jsfiddle.net/darioferrer/0ueu4dmy/

falsarella
  • 12,217
  • 9
  • 69
  • 115
Dario Ferrer
  • 804
  • 1
  • 8
  • 22
11

Expanding on @Finik's excellent answer, this fix is only applied to non-mobile devices. I tested in IE8, Chrome, and Firefox 22 - it works with very long or short content.

.modal {
  text-align: center;
}
@media screen and (min-device-width: 768px) {
  .modal:before {
    display: inline-block;
    vertical-align: middle;
    content: " ";
    height: 100%;
  }
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45
8

The most universal solution I wrote. Dynamicaly computes with dialog height. (Next step could be recalculating of dialogs' height on window resize.)

JSfiddle: http://jsfiddle.net/8Fvg9/3/

// initialise on document ready
jQuery(document).ready(function ($) {
    'use strict';

    // CENTERED MODALS
    // phase one - store every dialog's height
    $('.modal').each(function () {
        var t = $(this),
            d = t.find('.modal-dialog'),
            fadeClass = (t.is('.fade') ? 'fade' : '');
        // render dialog
        t.removeClass('fade')
            .addClass('invisible')
            .css('display', 'block');
        // read and store dialog height
        d.data('height', d.height());
        // hide dialog again
        t.css('display', '')
            .removeClass('invisible')
            .addClass(fadeClass);
    });
    // phase two - set margin-top on every dialog show
    $('.modal').on('show.bs.modal', function () {
        var t = $(this),
            d = t.find('.modal-dialog'),
            dh = d.data('height'),
            w = $(window).width(),
            h = $(window).height();
        // if it is desktop & dialog is lower than viewport
        // (set your own values)
        if (w > 380 && (dh + 60) < h) {
            d.css('margin-top', Math.round(0.96 * (h - dh) / 2));
        } else {
            d.css('margin-top', '');
        }
    });

});
Jan Renner
  • 106
  • 1
  • 5
7

This is quite old and specifically asks for a solution using Bootstrap 3, but for anyone wondering: from Bootstrap 4 on there is a built-in solution called .modal-dialog-centered. Here's the issue: https://github.com/twbs/bootstrap/issues/23638

So using v4 you just need to add .modal-dialog-centered to .modal-dialog to vertically center the modal:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Demo

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
Tobias
  • 4,034
  • 1
  • 28
  • 35
6

Found the perfect solution from here

$(function() {
    function reposition() {
        var modal = $(this),
            dialog = modal.find('.modal-dialog');
        modal.css('display', 'block');

        // Dividing by two centers the modal exactly, but dividing by three 
        // or four works better for larger screens.
        dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
    }
    // Reposition when a modal is shown
    $('.modal').on('show.bs.modal', reposition);
    // Reposition when the window is resized
    $(window).on('resize', function() {
        $('.modal:visible').each(reposition);
    });
});
Ismail Farooq
  • 6,309
  • 1
  • 27
  • 47
  • 1
    Thank you. Perfect for me with one change: dialog.css("margin-top", Math.max(0, ($(document).scrollTop() + (($(window).height() - dialog.height()) / 2)))); – Viacheslav Soldatov May 24 '18 at 00:14
4
$('#myModal').on('shown.bs.modal', function() {
    var initModalHeight = $('#modal-dialog').outerHeight(); //give an id to .mobile-dialog
    var userScreenHeight = $(document).outerHeight();
    if (initModalHeight > userScreenHeight) {
        $('#modal-dialog').css('overflow', 'auto'); //set to overflow if no fit
    } else {
        $('#modal-dialog').css('margin-top', 
        (userScreenHeight / 2) - (initModalHeight/2)); //center it if it does fit
    }
});
Ray Suelzer
  • 4,026
  • 5
  • 39
  • 55
  • With a couple of tweaks on the selectors this worked like a charm. `@$modal = $('.fade.in'); modalBox = @$modal.find('.modal-content'); initModalHeight = modalBox.outerHeight(); userScreenHeight = @$modal.outerHeight()` – juliangonzalez Nov 29 '18 at 15:29
4

Here's one other css only method that works pretty well and is based on this: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

sass:

.modal {
    height: 100%;

    .modal-dialog {
        top: 50% !important;
        margin-top:0;
        margin-bottom:0;
    }

    //keep proper transitions on fade in
    &.fade .modal-dialog {
        transform: translateY(-100%) !important;
    }
    &.in .modal-dialog {
        transform: translateY(-50%) !important;
    }
}
phazei
  • 5,323
  • 5
  • 42
  • 46
4

This works for me:

.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px;
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}
Liam
  • 5,033
  • 2
  • 30
  • 39
3

i have downloaded bootstrap3-dialog from bellow link and modified the open function in bootstrap-dialog.js

https://github.com/nakupanda/bootstrap3-dialog

Code

open: function () {
            !this.isRealized() && this.realize();
            this.updateClosable();
            //Custom To Vertically centering Bootstrap 
            var $mymodal = this.getModal();
            $mymodal = $mymodal.append('<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td align="center" valign="middle" class="centerModal"></td></tr></table>');
            $mymodal = $mymodal.find(".modal-dialog").appendTo($mymodal.find(".centerModal"));
            //END
            this.getModal().modal('show');
            return this;
        }

Css

.centerModal .modal-header{
    text-align:left;
}
.centerModal .modal-body{
    text-align:left;
} 
  • Here's a modification that can be applied in your own code, without having to change the original BSDialog source: https://gist.github.com/mahemoff/8ff6d3782d2da6f9cbb3 (just some modifications to the JS, also it's written in Coffee but you get the idea). – mahemoff Oct 22 '14 at 16:01
2

Try something like this:

.popup__overlay {
    position: fixed;
    left:  0;
    top:  0;
    width: 100%;
    height: 100%;
    z-index: 999;
    text-align: center
    }
.popup {
    display: inline-block;
    vertical-align: middle
    } 
1

You might want to check out this collection of methods for absolute centering a div: http://codepen.io/shshaw/full/gEiDt

Sevron
  • 493
  • 7
  • 18
1

A simple way. Work for me. Thks rensdenobel :) http://jsfiddle.net/rensdenobel/sRmLV/13/

<style>
.vertical-alignment-helper {
    display:table;
    height: 100%;
    width: 100%;
}
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
}
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
}
</style>
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="vertical-alignment-helper">
        <div class="modal-dialog vertical-align-center">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

                    </button>
                     <h4 class="modal-title" id="myModalLabel">Modal title</h4>

                </div>
                <div class="modal-body">...</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
</div>    
Tuyen Cao
  • 1,065
  • 9
  • 9
1

yet another solution which will set a valid position for each visible modal on window.resize event and on show.bs.modal:

(function ($) {
    "use strict";
    function centerModal() {
        $(this).css('display', 'block');
        var $dialog  = $(this).find(".modal-dialog"),
            offset       = ($(window).height() - $dialog.height()) / 2,
            bottomMargin = parseInt($dialog.css('marginBottom'), 10);

        // Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
        if(offset < bottomMargin) offset = bottomMargin;
        $dialog.css("margin-top", offset);
    }

    $(document).on('show.bs.modal', '.modal', centerModal);
    $(window).on("resize", function () {
        $('.modal:visible').each(centerModal);

    });
})(jQuery);
lenybernard
  • 2,399
  • 22
  • 22
1
var modalVerticalCenterClass = ".modal";
function centerModals($element) {
    var $modals;
    if ($element.length) {
        $modals = $element;
    } else {
        $modals = $(modalVerticalCenterClass + ':visible');
    }
    $modals.each( function(i) {
        var $clone = $(this).clone().css('display', 'block').appendTo('body');
        var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
        top = top > 0 ? top : 0;
        $clone.remove();
        $(this).find('.modal-content').css("margin-top", top);
    });
}
$(modalVerticalCenterClass).on('show.bs.modal', function(e) {
    centerModals($(this));
});
$(window).on('resize', centerModals);
user3477026
  • 241
  • 1
  • 3
  • 15
1

I know it's a bit late, but I am adding a new answer so that it doesn't get lost in the crowd. It's a cross-desktop-mobile-browser solution that works everywhere properly as it should.

It just needs the modal-dialog to be wrapped inside a modal-dialog-wrap class and need to have the following code additions:

.modal-dialog-wrap {
  display: table;
  table-layout: fixed;
  width: 100%;
  height: 100%;
}

.modal-dialog {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.modal-content {
  display: inline-block;
  text-align: left;
}

The dialog starts centered and in cases of large content it simply grows vertically until a scrollbar appears.

Here is a working fiddle for your pleasure!

https://jsfiddle.net/v6u82mvu/1/

scooterlord
  • 15,124
  • 11
  • 49
  • 68
1

.modal {
}
.vertical-alignment-helper {
    display:table;
    height: 100%;
    width: 100%;
}
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
}
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
}
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
</head>

<body>
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="vertical-alignment-helper">
        <div class="modal-dialog vertical-align-center">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

                    </button>
                     <h4 class="modal-title" id="myModalLabel">Modal title</h4>

                </div>
                <div class="modal-body">...</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

CSS:

.modal {
}
.vertical-alignment-helper {
    display:table;
    height: 100%;
    width: 100%;
}
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
}
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
}

HTML:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="vertical-alignment-helper">
        <div class="modal-dialog vertical-align-center">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

                    </button>
                     <h4 class="modal-title" id="myModalLabel">Modal title</h4>

                </div>
                <div class="modal-body">...</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
</div>

Reference: http://jsfiddle.net/rensdenobel/sRmLV/13/

LogicalAnt
  • 907
  • 3
  • 12
  • 28
Ejrr1085
  • 975
  • 2
  • 16
  • 29
0

Consider using the bootstrap-modal plugin found here - https://github.com/jschr/bootstrap-modal

The plugin will center all of your modals

Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63
  • ...unfortunately I had tried that but couldn't make it work properly - at least not with MY code. I guess that everyone needs to customise this to his needs! Thanks for the reply though. – scooterlord Feb 03 '14 at 18:10
0

For the centering, I don't get what's with the overly complicated solutions. bootstrap already centers it horizontally for you, so you don't need to mess with this. My solution is just set a top margin only using jQuery.

$('#myModal').on('loaded.bs.modal', function() {
    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return (($(window).outerHeight() / 2) - ($(this).outerHeight() / 2));
        }
    });
});

I've used the loaded.bs.modal event as I am remotely loading content, and using the shown.ba.modal event causes the height calculation to be incorrect. You can of course add in an event for the window being resized if you need it to be that responsive.

Scott Flack
  • 600
  • 7
  • 12
0

Very very easy way to achieve this concept and you will get modal always in the moddle of your screen by css as fllow : http://jsfiddle.net/jy0zc2jc/1/

you have to just modal class display as table by following css:

display:table

and modal-dialog as display:table-cell

see full working example in given fiddle

Innodel
  • 1,416
  • 12
  • 16
0

it's not that complicated.

please try this:

$(document).ready(function(){
    var modalId = "#myModal";
    resize: function(){
            var new_margin = Math.ceil(($(window).height() - $(modalId).find('.modal-dialog').height()) / 2);
            $(modalId).find('.modal-dialog').css('margin-top', new_margin + 'px');
    }
    $(window).resize(function(){
        resize();
    });
    $(modalId).on('shown.bs.modal', function(){
        resize();
    });
});
Mr. Sun Lin
  • 1,099
  • 9
  • 13
0

Use this simple script that centers the modals.

If you want you can set a custom class (ex: .modal.modal-vcenter instead of .modal) to limit the functionality only to some modals.

var modalVerticalCenterClass = ".modal";

function centerModals($element) {
    var $modals;
    if ($element.length) {
    $modals = $element;
    } else {
    $modals = $(modalVerticalCenterClass + ':visible');
}
$modals.each( function(i) {
    var $clone = $(this).clone().css('display', 'block').appendTo('body');
    var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
    top = top > 0 ? top : 0;
    $clone.remove();
    $(this).find('.modal-content').css("margin-top", top);
    });
}
$(modalVerticalCenterClass).on('show.bs.modal', function(e) {
    centerModals($(this));
});
$(window).on('resize', centerModals);

Also add this CSS fix for the modal's horizontal spacing; we show the scroll on the modals, the body scrolls is hidden automatically by Bootstrap:

/* scroll fixes */
.modal-open .modal {
    padding-left: 0px !important;
    padding-right: 0px !important;
    overflow-y: scroll;
}
Rakesh Vadnal
  • 975
  • 1
  • 10
  • 22
0

In mobile plantform it might look a little different, here's my code.

<div class="modal-container">
  <style>
  .modal-dialog{
    margin-top: 60%;
    width:80%;
    margin-left: 10%;
    margin-right: 10%;
    margin-bottom: 100%
  }
  @media screen and (orientation:landscape){
    .modal-dialog{
      margin-top: 70;
      width:80%;
      margin-left: 10%;
      margin-right: 10%;
      margin-bottom: 100%
    }
  }
  .modal-body{
    text-align: center;
  }
  .modal-body p{
    margin:14px 0px;
    font-size: 110%;
  }
  .modal-content{
    border-radius: 10px;
  }
  .modal-footer{
    padding:0px;
  }
  .modal-footer a{
    padding: 15px;
  }
  .modal-footer a:nth-child(1){
    border-radius: 0px 0px 0px 10px;
  }
  .modal-footer a:nth-child(2){
    border-radius: 0px 0px 10px 0px;
  }
  </style>
  <h2>Basic Modal Example</h2>
  <div data-toggle="modal" data-target="#myModal">Div for modal</div>
    <div class="modal fade" id="myModal" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-body">
            <p>确定要取消本次订单嘛?</p>
          </div>
          <div class="modal-footer">
            <div class="btn-group btn-group-justified">
              <a href="#" class="btn btn-default" data-dismiss="modal">取消</a>
              <a href="#" class="btn btn-default" data-dismiss="modal">确定</a>
            </div>
          </div>
        </div>
      </div>
    </div>
</div>
MartianMartian
  • 1,753
  • 1
  • 18
  • 26
0

set modal center to screen

.modal {
  text-align: center;
  padding: 0!important;
}
.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px;
}
.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}
Billu
  • 2,733
  • 26
  • 47
0

The simplest solution is to add modal dialog styles to the top of the page or import css with this code:

<style>
    .modal-dialog {
    position:absolute;
    top:50% !important;
    transform: translate(0, -50%) !important;
    -ms-transform: translate(0, -50%) !important;
    -webkit-transform: translate(0, -50%) !important;
    margin:auto 50%;
    width:40%;
    height:40%;
    }
</style>

Modal declaration:

    <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Modal usage:

<a data-toggle="modal" data-target="#exampleModalCenter">
 ...
</a>
Jackkobec
  • 5,889
  • 34
  • 34
0

This is responsive code and also open with different size in mobile view please check once.

.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 20%;
  vertical-align: middle;
  margin-right: -4px;
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}
Sumit Kumar Gupta
  • 2,132
  • 1
  • 22
  • 21