2013-12-12 56 views
0

我懷疑爲什麼在給定填充時div大小意外增加。我正在開發一個HTML保持高寬比。填充沒有按預期進行

這是我的HTML:

<body> 
<div id="container" class="containerOuter"> 
    <div class="main_container"> 
    <div class="top"> 
     <div class="top_inside"></div> 
    </div> 
    <div class="bottom"> 
     <div class="bottom_inside"></div> 
    </div> 
    </div> 
</div> 
</body> 

CSS:

html{ 
    width:100%; 
    height:100%; 
} 
body{ 
    width:100%; 
    height:100%; 
    padding:0; 
    margin:0; 
} 
.containerOuter { 
    background-color:silver; 
} 
.main_container{ 
    width:100%; 
    height:100%; 
} 
.top{ 
    width:96%; 
    height:76%; 
    padding:2%; 
    background:#F00; 
} 
.bottom{ 
    width:96%; 
    height:16%; 
    padding:2%; 
    background:#0F0;  
} 
.top_inside{ 
    width:100%; 
    height:100%;  
    background:#60C; 
} 
.bottom_inside{ 
    width:100%; 
    height:100%; 
    background:#C0C; 
} 

JS:

(function($) { 
    $.fn.keepRatio = function() { 
     var $this = $(this); 
     var ratio = 1.333333333; 
     function ReSize() { 
      var nw = $(window).height() * ratio; 
      $this.css('width', nw + 'px'); 
      $this.css('height', $(window).height() + 'px'); 
     } 
     $(window).resize(ReSize); 
     ReSize(); 
    } 
})(jQuery); 
$(document).ready(function(){ 
    $('#container').keepRatio(); 
}); 

當邊界框是用來尺寸減小

div { 
    -webkit-box-sizing:border-box; /* Safari/Chrome, other WebKit */ 
    -moz-box-sizing:border-box; /* Firefox, other Gecko */ 
    box-sizing:border-box;   /* Opera/IE 8+ */ 
} 

有人可以解釋這種意想不到的行爲嗎? 在此先感謝

+0

它正在做什麼,和你有什麼期待?你有一個小提琴或截圖幫助你的解釋? –

回答

0

嗯,這是瀏覽器默認解釋塊的方式,它將填充添加到塊的寬度。您應該使用CSS box-sizing

box-sizing: border-box; 
-moz-box-sizing: border-box; 
-webkit-box-sizing: border-box; 

更多信息有關box-sizing你可以找到w3schools.com

首先形象box-sizing設置爲content-box,第二個到border-box

Content boxBorder-box

CSS使用:

div { 
    border: 1px solid #000000; 
    padding: 15px; 
    width: 200px; 
} 
.border-box { 
    -moz-box-sizing: border-box; 
} 
+0

當使用邊框時,尺寸減小 – abduIntegral

+0

'box-sizing'指定應根據其內容(默認)或其包括邊框的總大小來測量框的大小。如果你使用'box-sizing:border-box',那麼你的div將會有一個設定的寬度,它會在內部填充和邊框,並且內容的寬度會減小。 – SpartakusMd

+0

@abduIntegral,我編輯了我的答案,檢查它。 – SpartakusMd