I’ve been working with modal boxes using Twitter Bootstrap. And the page I’m working on needs to be viewed in mobile devices. The modal looks nice and centered when viewed on desktop, but when run in mobile web browsers, it’s aligned to the top.
Someone on StackOverflow suggested the use of a helper div plus some custom CSS to align Bootstrap modals vertically.
Code for modal:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<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">×</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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
.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; height:inherit; /* To center horizontally */ margin: 0 auto; pointer-events: all; } |
Source: Vertically centering Bootstrap modal window