Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Vertically Centered Bootstrap Modals
<!DOCTYPE html>
<html lang="en">
<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="">
<!-- Optional theme -->
<link rel="stylesheet" href="">
<!-- 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 class="modal-body">
<p>One fine body&hellip;</p>
<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><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Latest compiled and minified JavaScript -->
<script src=""></script>
<script src=""></script>
<!-- Gist JavaScript -->
<script src="vertically-centered-bootstrap-modals.js"></script>
* 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('', reposition);
// Reposition when the window is resized
$(window).on('resize', function() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.