11

I use bootstrap modal plugin. But modal dialog is not shown in center. Why? my mistake?

http://dl.dropbox.com/u/573972/stackoverflow/bootstrap/modal.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <title>test</title>
  <meta name="description" content="">
  <meta name="author" content="">
  <!-- Mobile Specific-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- CSS-->
  <link rel="stylesheet" href="bootstrap.min.css">
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js'></script>
</head>
<body>
  <div id="login" class="modal">
    <div class="modal-header">
      <h3>Login to Room fuga</h3>
    </div>
    <div class="modal-body">
      hogehoge
    </div>
  </div>
  <script src="bootstrap.min.js">
  </script>
  <script>
$('#login').modal();
</script>
</body>
</html>
Andres I Perez
  • 75,075
  • 21
  • 157
  • 138
cpw
  • 299
  • 2
  • 4
  • 9

5 Answers5

18

I found this workarround to fix this issue:

$('#YourModal').modal().css(
            {
                'margin-top': function () {
                    return -($(this).height() / 2);
                }
            })

Source: https://github.com/twitter/bootstrap/issues/374

P48l0
  • 212
  • 1
  • 2
  • I removed the minus before ($this) to add a positive top margin instead of a negative margin, and that centered my dialog vertically in bootstrap 3. Using the solution directly seemed to move my dialog outside the visible area. – angularsen Dec 09 '13 at 17:45
  • For my case using: -($(window).height() / 2) gave me better results – Wilson Freitas Feb 26 '14 at 22:51
  • see the answer i have given just now – Innodel Dec 22 '14 at 04:42
10

if your twitter bootstrap modal dialog is not centered horizontally you can fix this via css.

just give the modal dialog a negative left margin that is half it's width like e.g. so:

 .modalDialogBlabla {
     margin: 0 0 0 -250px;
     width: 500px;
  }
nerdess
  • 10,051
  • 10
  • 45
  • 55
10

Capture the show event of the .modal and then calculate the new position:

$('body').on('show', '.modal', function(){
  $(this).css({'margin-top':($(window).height()-$(this).height())/2,'top':'0'});
});​

DEMO: http://jsfiddle.net/sonic1980/b2EHU/

Peter
  • 5,138
  • 5
  • 29
  • 38
2

Based on p4810's answer above but deal with where the user is on the screen too. Works with absolute positioning.

$('#YourModal').modal().css(
            {
                'margin-top': function () {
                    return window.pageYOffset-($(this).height() / 2 );
                }
            });
steve
  • 430
  • 5
  • 7
-15

Did you try:

$( "#login" ).dialog({
    modal: true
});

Ref: http://jqueryui.com//demos/dialog/modal.html

Osman
  • 73
  • 1
  • 7