Home > Article > Web Front-end > How to vertically center the Bootstrap modal box
Today I will teach you how to vertically center the Bootstrap modal box. I hope you will learn patiently.
The current version of bootstrap is 3.x. In the current version, the vertical centering attribute is not provided for bootstrap modal (modal box).
If you want the modal to be vertically centered, you currently need to handle it yourself.
Option 1. After the modal is displayed successfully, reset the position of margin-top
<p class="modal " id="myModal"> <p class="modal-dialog"> <p class="modal-content"> <p class="modal-header"> <button class="close" data-dismiss='modal'>×</button> <h4 class="modal-title">测试模态框标题</h4> </p> <p class="modal-body"> <p>内容…</p> </p> <p class="modal-footer"> <button class="btn btn-default" data-dismiss='modal'>关闭</button> </p> </p> </p> </p> <button class="btn btn-primary" data-toggle='modal' data-target='#myModal'> 点击测试弹框 </button>
Loading success event monitoring:
$('#myModal').on('shown.bs.modal', function () { var $this = $(this); var dialog = $this.find('.modal-dialog'); //此种方式,在使用动画第一次显示时有问题 //解决方案,去掉动画fade样式 var top = ($(window).height() - dialog.height()) / 2; dialog.css({ marginTop:top }); });
Option 2. Modify the source code. In the source code, set the position of margin-top in advance (recommended)
Note: This method is displayed when using the animation fade normal.
Modify the source code and set the dialog position
Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) // 是弹出框居中。。。 var $modal_dialog = $(this.$element[0]).find('.modal-dialog'); var m_top = ( $(window).height() - $modal_dialog.height() )/2; $modal_dialog.css({'margin': m_top + 'px auto'}); }
Related recommendations:
bootstrap study notes bootstrap layout method_html/css_WEB-ITnose
Bootstrap Getting Started Notes (Zero) Introduction to Bootstrap_html/css_WEB-ITnose
The above is the detailed content of How to vertically center the Bootstrap modal box. For more information, please follow other related articles on the PHP Chinese website!