2015-04-07 22 views
0

我已經看到了將模式寬度限制爲頁面的某個百分比或某個列寬的解決方案,但有可能簡單地獲取最適合的模式 - 即使用模態內容的最小寬度?Bootstrap模式適合寬度和水平居中

我試圖添加width: auto;沒有成功。

參見:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true" style="width:auto"> 
    <div class="modal-dialog" style="width:auto"> 
    <div class="modal-content"> 
     <img src="http://pdf.buildasign.com/upload/images/templateImages/TC17819031-42-260-195-7357-11-SharedDesign.png"> 
     <br> 
     <p>hello</p> 
    </div> 
    </div> 
</div> 

jsfiddle

我想模態寬度是頂端的橫幅(加上一些裕度),爲中心的模態和寬度/定心保持自身如果頁面寬度改變。

謝謝!

+0

你嘗試添加寬度自動模態內容呢? –

+0

你將無法使用CSS來做到這一點;該模式需要左側和右側邊距的定義寬度才能起作用。 –

回答

0

下面是一個全面的解決方案,保存原始寬度並使用它計算顯示的事件和文檔大小的寬度和左邊距百分比。最初隱藏對話框以防止閃爍效應。

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch</button> 
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true"> 
    <div class="modal-dialog"> 
     <div class="modal-content" style="display:none;"> 
     <img src="http://pdf.buildasign.com/upload/images/templateImages/TC17819031-42-260-195-7357-11-SharedDesign.png"> 
     <br> 
     <p>hello</p> 
    </div> 
</div> 

function hCenterModals() { 
    function toP(n) { return (n * 100).toFixed() + '%'; } 

    $('.modal').each(function() { 
     var modalDialog = $(this).find('.modal-dialog'), 
      modalContent = $(this).find('.modal-content'); 

     // get/save minWidth to data (for resize) 
     var minWidth = modalDialog.data('minWidth'); 
     if (!minWidth) { 
      minWidth = modalContent.width(); 
      if (minWidth > 0) { 
       modalDialog.data('minWidth', minWidth); 
       console.log('saved ' + minWidth); 
      } else { 
       minWidth = 0; 
      } 
     } 

     if (minWidth>0 && modalDialog.is(':visible')) { 
      var widthFrac = minWidth/$(window).width(); 

      modalDialog.css({ 
       'width': toP(widthFrac), 
       'margin-left': toP((1 - widthFrac)/2) 
      }); 
     } 
    }); 
} 

$('#myModal').on('shown.bs.modal', function (e) { 
    hCenterModals(); 
    var modalContent = $(this).find('.modal-content'); 
    modalContent.show(); 
}); 

$(window).resize(hCenterModals).trigger("resize"); 

看到jsfiddle

2

你需要處理shown.bs.modal事件,並調整其大小div來什麼,像這樣:

http://jsfiddle.net/vyw2zvfu/2/

$(function(){ 

    $('#myModal').on('shown.bs.modal', function(e){ 

     var width = $(this).find('.modal-content img').width(); 

     $(this).animate({ 'width': width+25 }); 

    }); 

}); 

你會發現模式開始在它的默認大小,但是。

+1

不錯的解決方案,但'$(this).css({'width':width + 25});',稍好於'$(this).animate({'width':width + 25});'。但是,當模式加載時仍然可以看到默認寬度。 –

+0

@AlexanderSolonik定義「略好」?最終結果是一樣的,如果你檢查模態的標記,比如說Firebug。 –

+0

!好css()不添加動畫像animate().. –