191

I would like to center my modal on the viewport (middle) I tried to add some css properties

 .modal { position: fixed; top:50%; left:50%; }   

I'm using this example http://jsfiddle.net/rniemeyer/Wjjnd/

I tried

$("#MyModal").modal('show').css(
    {
        'margin-top': function () {
            return -($(this).height() / 2);
        },
        'margin-left': function () {
            return -($(this).width() / 2);
        }
    })
madth3
  • 7,275
  • 12
  • 50
  • 74
user2613813
  • 1,951
  • 2
  • 13
  • 10
  • Try to override `.modal.fade.in` as well – haim770 Aug 05 '13 at 08:54
  • Try with this: https://github.com/jschr/bootstrap-modal/ – John Magnolia Nov 04 '14 at 16:07
  • 3
    Try this http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/ I use : .modal.fade.in { top: 50%; transform: translateY(-50%); } – jowan sebastian Nov 13 '14 at 17:33
  • Added [flexbox solution](/questions/18053408/vertically-centering-bootstrap-modal-window/41375185#41375185) (the `translateY(-50%)` one makes top of modal inaccessible when modal contents are taller than device height). – tao Dec 30 '16 at 23:15
  • 1
    As of bootstrap 4 modal-dialog-centered was added that this is no longer necessary. Please review that answer below. – jcaruso Jul 05 '18 at 15:08

33 Answers33

266

This does the job : http://jsfiddle.net/sRmLV/1140/

It uses a helper-div and some custom css. No javascript or jQuery required.

HTML (based on Bootstrap's demo-code)

<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>

CSS

.vertical-alignment-helper {
    display:table;
    height: 100%;
    width: 100%;
    pointer-events:none; /* This makes sure that we can still click outside of the modal to close it */
}
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
    pointer-events:none;
}
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    max-width:inherit; /* For Bootstrap 4 - to avoid the modal window stretching full width */
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
    pointer-events: all;
}
Jay Regal
  • 3,243
  • 1
  • 16
  • 18
  • With this solution, because of the height: 100%; and width: 100%; you can't close the modals by clicking out of the modals. Can you think of a fix for this @Rens de Nobel? – pcatre Oct 16 '14 at 13:30
  • 1
    Ok this solution appears to work great (except that it stops me from closing the modals by clicking out of them). But somehow it makes some of my e2e tests with protractor fail (and I can't find the reason why, it does not feel like it is a bug on this). Anyway I'm going back to the javascript answer so I don't lose more time on this. But like I said, this appears to work fine, just warning people doing e2e tests with protractor to watch out. – pcatre Oct 17 '14 at 09:52
  • 3
    @pcatre, thanks for the tip ! I've updated the code with a fix for this. Setting pointer-events:none; on the alignment-classes does the trick. Tested in IE11, Latest Chrome and Firefox and iOS Safari. – Jay Regal Oct 17 '14 at 12:03
  • it does not allow me to click on tab i put inside the modal. but when i remove css, it then allows me. – Smith Oct 25 '14 at 03:10
  • Now you can't interact with anything inside the modal. Clicking on it anywhere dismisses it. – Nick Retallack Feb 18 '15 at 04:49
  • It now works due to the pointer-events: all; in the modal-content class. Thanks for updating @Nick Retallack – Jay Regal Feb 20 '15 at 17:19
  • Great solution, but can be improved. First, instead of using pointer-events that are not supported in older browsers I just added data-dismiss="modal" to .vertical-alignment-helper div (it makes BS to close dialog when it is clicked). Second, for .modal-content media query should be used and horizontal margin should be set to 10px on mobile screens, and auto on big screens. – snovity May 25 '15 at 09:03
  • Hi snovity, sounds good. Can you provide us with a working example (e.g. on jsfiddle)? – Jay Regal May 25 '15 at 13:31
  • Rens de Nobel, after some testing, idea with data-dismiss="modal" turned out to be not that good :) Problem is that when you click on a dialog itself, it also closes because of event propagation to .vertical-alignment-helper. For it to work js is needed to stop propagation from dialog to its parent elements. So I went back to your solution (the only difference is that .vertical-align-center need no prevent-events, it inherits it from .vertical-alignment-helper) Second part with media queries and margins works as expected. – snovity May 26 '15 at 11:23
  • 4
    Not sure if this has been updated since the comments of users saying it doesn't work, on click of inside modal elements, but this is 100% working for me as of now, using the example in the Fiddle above. Thanks so much for your help and all the comments above. – Michael G Jun 27 '15 at 19:39
  • The disadvantage of this solution is that if the modals are big and occupy entire screen height specially in mobile scrolling does not work. Any solution for that. – Jyotirmoy Pan Feb 08 '16 at 19:36
  • Mobile scrolling works fine on the devices I have here...@JyotirmoyPan, what device are you using? – Jay Regal Jan 25 '17 at 11:25
  • works perfectly, thank you. I eliminated a div put `vertical-alignment-helper` in ` – Jeff Bluemel May 17 '17 at 17:46
  • yw :) For the sake of readability, I like to keep those divs separate – Jay Regal May 18 '17 at 08:55
  • 5
    As of bootstrap 4 modal-dialog-centered was added that this is no longer necessary. Please review that answer below. – jcaruso Aug 02 '18 at 14:13
  • This is probably the best solution for Bootstrap 3 users – Tim Bogdanov Jun 25 '21 at 17:09
93

Because gpcola's answer didn't work for me, I edited a bit so its works now. I used "margin-top" instead of transform. Also, i use the "show" instead of "shown" event because after it gave me a very bad jump of positioning (visible when you have bootstrap animations on). Be sure to set the display to "block" before positioning, otherwise $dialog.height() will be 0 and the modal will not be centered completely.

(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));
Arany
  • 1,238
  • 11
  • 11
  • 6
    This one is perfect! Just instead of $(document).height() its correct to use $(window).height() in line 4. Plus I would change the last line to: `$('.modal:visible').each(centerModal);` – Denis Chmel Mar 27 '14 at 09:06
  • It work for me perfectly, thank you. when we use this code, we also must set padding top and bottom of modal-dialog to 0px ,to perfect centering. – mina morsali May 10 '14 at 12:31
  • This breaks if the modal is taller than the height of the window. So I added the following line right before setting the margin-top of the dialog: `if(offset < 0) offset = 0;` I'm pasting the entire block into an answer case that's not clear! – jetlej May 21 '14 at 23:30
  • I added some further changes to keep the top margin equal to the bottom margin of the modal, in the answer below – jetlej May 22 '14 at 00:05
  • Perfect, was missing $(this).css('display', 'block'); all the time and thought why height was 0. – Jānis Gruzis Jul 23 '14 at 11:34
  • Simple solution! Worked for me, tks! :D – Rafa Bytes Jan 16 '15 at 18:25
  • The inner function worked perfectly when I tried, but your IIFE (immediately invoked function expression) has a typo. The `(jQuery)` should be inside the enclosing parens, directly after the closing function brace `}` – VictorB Jul 24 '15 at 07:33
87

This is what I did for my app. If you take a look at the following classes in the bootstrap.css file .modal-dialog has a default padding of 10px and @media screen and (min-width: 768px) .modal-dialog has a top padding set to 30px. So in my custom css file I set my top padding to be 15% for all screens without specifying a media screen width. Hope this helps.

.modal-dialog {
  padding-top: 15%;
}
user1279047
  • 1,403
  • 10
  • 7
71

Best way I found for all HTML5 browsers:

body.modal-open .modal {
    display: flex !important;
    height: 100%;
} 

body.modal-open .modal .modal-dialog {
    margin: auto;
}
taha shahid
  • 717
  • 5
  • 5
  • 2
    I liked this solution, very clean. Not sure about desktop or older versions of Safari but it seems to be fine on iOS 8. – Nicolas Galler Sep 18 '15 at 13:22
  • 1
    Yes I agree with @NicolasGaller. It works well for me too. I tested in Chrome and Firefox. It works well. – Manjunath Reddy Apr 12 '16 at 07:13
  • 2
    This is a great css only progressive enhancement. No js required and any browser that doesn't support flexbox will get the default bootstrap modal placement. – Craig Harshbarger May 04 '16 at 19:55
  • Close, but it breaks being able to close modals when there is more than one on the page. See my answer below to fix. – Robert McKee May 23 '16 at 18:34
  • Does not work on IE 11. `body.modal-open .modal .modal-dialog` needs to have an explicit height for vertical alignment to work properly. Adding `height: 100px` works but limits the usefulness of this solution. – bernie Sep 30 '16 at 17:24
  • 1
    Update: Adding `align-items: center;` to `body.modal-open .modal` seems to work. – bernie Sep 30 '16 at 18:33
24
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="table">
        <div class="table-cell">
            <div class="modal-dialog">
                <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>
</div>

// Styles

.table {
 display: table;
 height:100%;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
user3389
  • 479
  • 5
  • 10
  • 3
    This is the universal answer. I don't know why noone voted for it. – Csaba Toth Dec 06 '14 at 03:53
  • 3
    I went through at least 4 SO entries each with a dozen of proposals. BTW, at the age of HTML5 this should be built in functionality to some framework at least. Instead of juggling. – Csaba Toth Dec 06 '14 at 03:57
  • 1
    Also note: if you say width:100% for the table style, you'll get horizontal centering (in case if the modal is not overflow hidden). – Csaba Toth Dec 06 '14 at 04:06
  • 2
    Best answer by far. This creates a scrollbar but you can disable it by making .modal-open .modal { overflow-y: hidden; } – Christophe Sep 16 '15 at 22:24
24

As of Bootstrap 4 the following class was added to achieve this for you without JavaScript.

modal-dialog-centered

You can find their documentation here.

Thanks v.d for pointing out you need to add both .modal-dialog-centered to .modal-dialog to vertically center the modal.

jcaruso
  • 2,364
  • 1
  • 31
  • 64
  • 5
    This is the best answer for bootstrap 4. – broc.seib Jun 25 '19 at 16:46
  • by adding both modal-dialog and modal-dialog-centered has better result – Vahid Dec 18 '19 at 14:09
  • 2
    @v.d thats understood given the documentation say "Add .modal-dialog-centered to .modal-dialog to vertically center the modal." I'll update my answer to reflect that as well for those who didn't catch that. – jcaruso Dec 18 '19 at 19:38
15

this Works for me perfectly:

.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;
}

complete Demo URL : https://codepen.io/dimbslmh/full/mKfCc

14

The top parameter is being overridden in .modal.fade.in to force the value set in your custom declaration, add the !important keyword after top. This forces the browser to use that value and ignore any other values for the keyword. This has the drawback that you can't override the value anywhere else.

.modal {
    position: fixed;
    top: 50% !important;
    left: 50%;
}
Alexander Varwijk
  • 2,075
  • 18
  • 21
12

Because most of the answer here didn't work, or only partially worked:

body.modal-open .modal[style]:not([style='display: none;']) {
    display: flex !important;
    height: 100%;
} 

body.modal-open .modal[style]:not([style='display: none;']) .modal-dialog {
    margin: auto;
}

You have to use the [style] selector to only apply the style on the modal that is currently active instead of all the modals. .in would have been great, but it appears to be added only after the transition is complete which is too late and makes for some really bad transitions. Fortunately it appears bootstrap always applies a style attribute on the modal just as it is starting to show so this is a bit hacky, but it works.

The :not([style='display: none;']) portion is a workaround to bootstrap not correctly removing the style attribute and instead setting the style display to none when you close the dialog.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57
11

you can use:

.modal {
    position: fixed;
    top: 50% !important;
    left: 50%;
    transform: translate(-50%, -50%);
}

to center it both vertically and horizontally.

Aryeh Armon
  • 2,137
  • 2
  • 22
  • 37
  • 2
    This is the true "how to center something" with CSS without using Flex. The fact that the context is Bootstrap or a modal should be irrelevant. All other answers are way too overkill. – ESR Aug 23 '17 at 03:44
  • 1
    With this method, if the modal is taller than device screen height, the top of the modal becomes inaccessible. – tao Apr 13 '18 at 19:17
8

You can achieve vertical alignment center on Bootstrap 3 modal like that :

.modal-vertical-centered {
  transform: translate(0, 50%) !important;
  -ms-transform: translate(0, 50%) !important; /* IE 9 */
  -webkit-transform: translate(0, 50%) !important; /* Safari and Chrome */
}

and add this css class to the "modal-dialog" container

<div class="modal-dialog modal-vertical-centered">
...

jsFiddle working example : http://jsfiddle.net/U4NRx/

Dorian
  • 22,759
  • 8
  • 120
  • 116
EGurelli
  • 406
  • 5
  • 6
  • How exactly does it center the dialog vertically ? – gkalpak Nov 18 '13 at 20:32
  • Works great in most places, but does not work in wrapped html5 applications lower than Android 4.4. – Joshua Feb 25 '14 at 21:49
  • 4
    My modal was down the page with this – Dorian May 13 '14 at 18:44
  • 2
    YUP! I use : .modal.fade.in { top: 50%; transform: translateY(-50%); } – jowan sebastian Nov 13 '14 at 17:32
  • Just modify 50% to 15% and then the dialog will be in the center of the window. .modal-vertical-centered { transform: translate(0, 15%) !important; -ms-transform: translate(0, 15%) !important; /* IE 9 */ -webkit-transform: translate(0, 15%) !important; /* Safari and Chrome */ } – Haimei Jan 28 '15 at 14:58
  • Doesn't work at all, if the size of the dialog changes the dialog will just move lower! – Roger Far Mar 01 '15 at 21:54
8

The cleanest and simplest way to do this is to use Flexbox! The following will vertically align a Bootstrap 3 modal in the center of the screen and is so much cleaner and simpler than all of the other solutions posted here:

body.modal-open .modal.in {
  display: flex !important;
  align-items: center;
}

NOTE: While this is the simplest solution, it may not work for everyone due to browser support: http://caniuse.com/#feat=flexbox

It looks like (per usual) IE lags behind. In my case, all the products I develop for myself or for clients are IE10+. (it doesn't make sense business wise to invest development time supporting older versions of IE when it could be used to actually develop the product and get the MVP out faster). This is certainly not a luxury that everyone has.

I have seen larger sites detect whether or not flexbox is supported and apply a class to the body of the page - but that level of front-end engineering is pretty robust, and you'd still need a fallback.

I would encourage people to embrace the future of the web. Flexbox is awesome and you should start using it if you can.

P.S. - This site really helped me grasp flexbox as a whole and apply it to any use case: http://flexboxfroggy.com/

EDIT: In the case of two modals on one page, this should apply to .modal.in

Greg Blass
  • 3,523
  • 29
  • 42
8

Advantages:

  • modal contents accessible even when taller than device
  • doesn't use display:table-cell (that's not meant for layouts)
  • does not require any modifications to default Bootstrap 3 modal markup
  • positioning is pure CSS. The JS is added for closing the modal on click/tap below and above it
  • I included the un-prefixed SCSS for those who use gulp or grunt

// closes the modal on click/tap below/above the modal

$('.modal-dialog').on('click tap', function(e){
    if (e.target.classList.contains('modal-dialog')) {
    $('.modal').modal('hide');
  }
})
.modal-dialog {
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
     -moz-box-orient: vertical;
     -moz-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
     -moz-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  overflow-y: auto;
  min-height: -webkit-calc(100vh - 60px);
  min-height: -moz-calc(100vh - 60px);
  min-height: calc(100vh - 60px);
}
@media (max-width: 767px) {
  .modal-dialog {
    min-height: -webkit-calc(100vh - 20px);
    min-height: -moz-calc(100vh - 20px);
    min-height: calc(100vh - 20px);
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</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>

Note: I intend to keep this answer up to date with the latest specs of Bootstrap 3. For a Bootstrap 4 solution, see this answer (for now they are more or less the same, but in time they might diverge). If you find any bug or problem with it, let me know and I will update. Thanks.


Clean, un-prefixed SCSS (for use with gulp/grunt):

.modal-dialog {
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow-y: auto;
  min-height: calc(100vh - 60px);
  @media (max-width: 767px) {
    min-height: calc(100vh - 20px);
  }
}
Community
  • 1
  • 1
tao
  • 82,996
  • 16
  • 114
  • 150
3

Yet another CSS solution. Does not Work for popups that are bigger than the view port.

.modal-dialog {
    position: absolute;
    right: 0;
    left: 0;
    margin-top: 0;
    margin-bottom: 0; 
}
.modal.fade .modal-dialog {
    transition: top 0.4s ease-out;
    transform: translate(0, -50%);
    top: 0;
}
.modal.in .modal-dialog {
    transform: translate(0, -50%);
    top: 50%;
}

In .modal-dialog class overriding the position to absolute(from relative) and centering the content right:0, left: 0

In .modal.fade .modal-dialog , .modal.in .modal-dialog setting the transition animation over top rather than on translate.

margin-top moves the popup slightly below the center in case of small popup and in case of long popups, the modal is stuck with header. Hence margin-top:0, margin-bottom:0

Need to further refine it.

pravin
  • 1,106
  • 1
  • 18
  • 27
3

For those who are using angular-ui bootstrap can add the below classes based on above info:

Note: No other changes are needed and it shall resolve all modals.

// The 3 below classes have been placed to make the modal vertically centered
.modal-open .modal{
    display:table !important;
    height: 100%;
    width: 100%;
    pointer-events:none; /* This makes sure that we can still click outside of the modal to close it */
}

.modal-dialog{
    display: table-cell;
    vertical-align: middle;
    pointer-events: none;
}

.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;
    pointer-events: all;
}
Jyotirmoy Pan
  • 837
  • 2
  • 10
  • 28
3

No need to us javascript. Boostrap modal adds .in class when it appears. Just modify this class combination with modalclassName.fade.in with flex css and you are done.

add this css to center your modal vertically and horizontally.

.modal.fade.in {
    display: flex !important;
    justify-content: center;
    align-items: center;
}
.modal.fade.in .modal-dialog {
    width: 100%;
}
No one
  • 1,130
  • 1
  • 11
  • 21
3

.modal.in .modal-dialog {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}
3

Vertically centered Add .modal-dialog-centered to .modal-dialog to vertically center the modal

Launch demo modal

<!-- 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>
Tayyab Roy
  • 423
  • 5
  • 7
2

My choice, just a little CSS: ( NOT working in IE8 )

.modal.fade .modal-dialog {
    transform: translate(-50%, -80%);
}

.modal.in .modal-dialog {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    margin-top: 0px;
}

You can play with the first rule to change how the modal appears.

Using: Bootstrap 3.3.4

John Bernardsson
  • 1,751
  • 1
  • 17
  • 19
2

Simply add the following CSS to you existing one,It works fine for me

.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;
}
Shankar Prakash G
  • 1,099
  • 18
  • 34
2

Based on Arany's answer, but also accounting for page scroll.

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

        $dialog.css('margin-top', offset < marginBottom ? marginBottom : offset);
    }

    $(document).on('show.bs.modal', '.modal', positionModals);

    $(window).on('resize', function(e) {
        $('.modal:visible').each(positionModals);
    });
}(jQuery));
Community
  • 1
  • 1
mathieu
  • 41
  • 3
2

I think this is a bit cleaner pure CSS solution than Rens de Nobel's solution. Also this does not prevent from closing the dialog by clicking outside of it.

http://plnkr.co/edit/JCGVZQ?p=preview

Just add some CSS class to DIV container with .modal-dialog class to gain higher specificity than the bootstraps CSS, e.g. .centered.

HTML

<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
  <div class="modal-dialog centered modal-lg">
    <div class="modal-content">
      ...
    </div>
  </div>
</div>

And make this .modal-dialog.centered container fixed and properly positioned.

CSS

.modal .modal-dialog.centered {
    position: fixed;
    bottom: 50%;
    right: 50%;
    transform: translate(50%, 50%);
}

Or even simpler using flexbox.

CSS

.modal {
    display: flex;
    align-items: center;
    justify-content: center;
}
Ismail Farooq
  • 6,309
  • 1
  • 27
  • 47
Vit Koumar
  • 41
  • 4
  • This flexbox version doesn't work as expected. Testing on the latest Chrome (52.0.x), the .modal-dialog is centered properly but its content interaction seems frozen on the old place (weirdly). However, you can try to use this technique right on .modal-dialog (not on .modal), and with some other properties, it does seem to work. =) – giovannipds Aug 30 '16 at 16:59
1

This works in BS3, not tested in v2. It centers the modal vertically. Note that it will transition there - if you want it to just appear in position edit CSS transition property for .modal-dialog

centerModal = function() {
    var $dialog = $(this).find(".modal-dialog"),
        offset = ($(window).height() - $dialog.height()) / 2;

    // Center modal vertically in window
    $dialog.css({
        'transform': 'translateY(' + offset + 'px) !important',
    });
};

$('.modal').on('shown.bs.modal', centerModal);
$(window).on("resize", function() {
    $('.modal').each(centerModal);
});
gpcola
  • 969
  • 5
  • 15
  • 26
1
e(document).on('show.bs.modal', function () {
        if($winWidth < $(window).width()){
            $('body.modal-open,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',$(window).width()-$winWidth)
        }
    });
    e(document).on('hidden.bs.modal', function () {
        $('body,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',0)
    });
TLama
  • 75,147
  • 17
  • 214
  • 392
Tomtom
  • 11
  • 1
1

This takes Arany's answer and makes it work if the modal is taller than the height of the screen:

function centerModal() {
    $(this).css('display', 'block');
    var $dialog = $(this).find(".modal-dialog");
    var offset = ($(window).height() - $dialog.height()) / 2;
    //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
    var bottomMargin = $dialog.css('marginBottom');
    bottomMargin = parseInt(bottomMargin);
    if(offset < bottomMargin) offset = bottomMargin;
    $dialog.css("margin-top", offset);
}

$('.modal').on('show.bs.modal', centerModal);
$(window).on("resize", function () {
    $('.modal:visible').each(centerModal);
});
jetlej
  • 3,382
  • 6
  • 29
  • 41
1

To add vertical modal centering to bootstrap modal.js I added this at the end of the Modal.prototype.show function:

var $modalDialog = $('.modal-dialog'),
        modalHeight = $modalDialog.height(),
        browserHeight = window.innerHeight;

    $modalDialog.css({'margin-top' : modalHeight >= browserHeight ? 0 : (browserHeight - modalHeight)/2});
andersra
  • 1,103
  • 2
  • 13
  • 33
  • Won't work well if the dialog changes height once shown, due to page resizing or stuff inside it expands/collapses. – Dirbaio Apr 17 '15 at 04:54
0

To make Modal verically Align Middle All dialog.

/* Note:

1.Even you don't need to assign selector , it will find all modal from the document and make it vertically middle

2.To avoid middle some specific modal to be it center you can use :not selector in click event

*/

 $( "[data-toggle='modal']" ).click(function(){
     var d_tar = $(this).attr('data-target'); 
     $(d_tar).show();   
     var modal_he = $(d_tar).find('.modal-dialog .modal-content').height(); 
     var win_height = $(window).height();
     var marr = win_height - modal_he;
     $('.modal-dialog').css('margin-top',marr/2);
  });

From Milan Pandya

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

Another CSS answer to this question...
This solution uses CSS only to achieve the desired effect while still maintaining the ability to close the modal by clicking outside of it. It also allows you to set .modal-content height and width maximums so that your pop-up won't grow beyond the viewport. A scroll will automatically appear when the content grows beyond the modal size.

note:
The Bootstrap recommended .modal-dialog div should be omitted in order for this to work properly (doesn't seem to break anything). Tested in Chrome 51 and IE 11.

CSS Code:

.modal {
   height: 100%;
   width: 100%;
}

.modal-content {
   margin: 0 auto;
   max-height: 600px;
   max-width: 50%;
   overflow: auto;
   transform: translateY(-50%);
}

EDIT: The .modal-dialog class allows you to choose whether or not a user can close the modal by clicking outside of the modal itself. Most modals have an explicit 'close' or 'cancel' button. Keep this in mind when using this workaround.

dsanchez
  • 1,038
  • 9
  • 9
0

The best solution to centralize your modal with width and height is, in css add and in modal add this 'centralize' as a class..

.centralize{
   position:absolute;
   left:50%;
   top:50%;

   background-color:#fff;
   transform: translate(-50%, -50%);
   width: 40%; //specify watever u want
   height: 50%;
   }
0

Just ignore all the Upper methods. It will work with Bootstrap versions 4 and 5.

openModal(template: TemplateRef) { this.modalRef = this.modalService.show(template, {class: 'modal-sm modal-dialog-centered'}); }

Bluerain
  • 477
  • 5
  • 9
0

Bootstrap 5 comes now with the class modal-dialog-centered this will center the modal for you

Max
  • 120
  • 1
  • 9
-7

after 4 hours I found the solution. To center modal in different resolutions (desktop, tablets, smartphones):

index.php

<! - Bootstrap core CSS ->
     <link href=".../css/bootstrap-modal-bs3patch.css" rel="stylesheet">
     <link href=".../css/bootstrap-modal.css" rel="stylesheet">

The file bootstrap-modal-bs3patch.css I downloaded it from https://github.com/jschr/bootstrap-modal

I then modified this file. Css as follows:

body.modal-open,
. modal-open. navbar-fixed-top,
. modal-open. navbar-fixed-bottom {
   margin-right: 0;
}


. {modal
   padding: 0;
}

. modal.container {
   max-width: none;
}

@ media (min-width: 768px) and (max-width: 992px) {

. {modal-dialog
background-color: black;
position: fixed;
top: 20%! important;
left: 15%! important;
}
}

@ media (min-width: 992px) and (max-width: 1300px) {

. {modal-dialog
background-color: red;
position: fixed;
top: 20%! important;
left: 20%! important;
}
}

@ media (min-width: 1300px) {

. {modal-dialog
background-color: # 6e7ec3;
position: fixed;
top: 40%! important;
left: 35%! important;
}
}

I did tests on different resolutions and it works!

Slo74
  • 7