DIV CSS 佈局教程網

Bootstrap 彈出框無法垂直居中?兩種修法一次講清
編輯:關於JavaScript     

用過 Bootstrap modal 的人大概都有這個困惑:好端端一個彈出框,怎麼就是沒法垂直居中?它的預設樣式是 top: 10%,頁面短的時候還看不出問題,一旦內容變長、需要滾動,位置就顯得相當彆扭。

這裡提供兩種修法,一種改 CSS,一種改 JS。

方案一:改 CSS

在樣式表中找到這一段:

.modal.fade.in {
  top: 10%;
}

把它改掉即可。由於這是全域樣式,改動會影響所有 modal。若只想針對某一個彈出框調整,可以在頁面中覆寫特定 id:

<style>
#myModal-help {
  top: 300px;
}
</style>

#myModal-help 就是該 modal 的 id,這樣設定之後只有它會被影響。

方案二:改 JS

筆者使用的是 bootstrap-modal.js;若你用的是 bootstrap.js 或 bootstrap.min.js 也無妨,找到對應位置即可。

var left = ($(document.body).width() - that.$element.width()) / 2;

var top = ($(document.body).height() - that.$element.height()) / 2;

var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
// 滾動條補償
var top = (window.screen.height / 4) + scrollY - 120;

console.log(left);

that.$element
  .addClass('in')
  .attr('aria-hidden', false)
  .css({
    left: left,
    top: top,
    margin: "0 auto"
  });

that.enforceFocus();

把上面那幾行補進去,所有彈出框就都垂直居中了。這裡的 scrollY 是關鍵——不加上滾動量,頁面往下捲之後 modal 會跑到視窗外。

更省事的做法:直接用 Flexbox

如果不必支援 IE8 以下的舊瀏覽器,其實完全不需要動 Bootstrap 的原始碼。只要覆寫幾行樣式,就能得到真正的動態居中:

<style>
.modal {
  display: flex !important;
  align-items: center;
  justify-content: center;
}
.modal-dialog {
  margin: 0 auto;
  width: auto;
  max-width: 800px;
}
</style>

这种做法的好處是它會隨視窗高度自動調整,不像固定 top 值那樣在視窗極小或極大時失準。Bootstrap 4 之後官方也已改用類似思路處理這個問題。

要注意的是,display: flex 會與 modal 隱藏時的 display: none 相衝,因此加上 !important 或改用 Bootstrap 提供的 modal-dialog-centered 類別(Bootstrap 4.1+)會更穩妥。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved