In this example you will learn, how to align Bootstrap modal vertically center. This solution will dynamically adjust the alignment of the modal and always keep it in the center of the page even if the user resizes the browser window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Vertical Center Alignment of Bootstrap Modal Dialog</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-theme.min.css"> <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script> <script src="js/bootstrap.min.js"></script> <script> $(document).ready(function(){ function alignModal(){ var modalDialog = $(this).find(".modal-dialog"); /* Applying the top margin on modal dialog to align it vertically center */ modalDialog.css("margin-top", Math.max(0, ($(window).height() - modalDialog.height()) / 2)); } // Align modal when it is displayed $(".modal").on("shown.bs.modal", alignModal); // Align modal when user resize the window $(window).on("resize", function(){ $(".modal:visible").each(alignModal); }); }); </script> </head> <body> <!-- Button HTML (to Trigger Modal) --> <p><a href="#myModal" class="btn btn-lg btn-primary" data-toggle="modal">Launch Demo Modal</a></p> <!-- Modal HTML --> <div id="myModal" class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title">Confirmation</h4> </div> <div class="modal-body"> <p>Do you want to save changes you made to document before closing?</p> <p class="text-warning"><small>If you don't save, your changes will be lost.</small></p> </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> </body> </html> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.