Skip to content

Instantly share code, notes, and snippets.

@CrandellWS
Forked from claviska/vertically-centered-bootstrap-modals.js
Last active October 17, 2015 22:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrandellWS/8bcd88c6eca4a8260e16 to your computer and use it in GitHub Desktop.
Save CrandellWS/8bcd88c6eca4a8260e16 to your computer and use it in GitHub Desktop.
Vertically Centered Bootstrap Modals
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
</head>
<body>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<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">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body&hellip;</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><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Latest compiled and minified JavaScript -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Gist JavaScript -->
<script src="vertically-centered-bootstrap-modals.js"></script>
</body>
</html>
/**
* Vertically center Bootstrap 3 modals so they aren't always stuck at the top
*/
$(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);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment