2014-10-10 184 views
1

我遇到以下問題。100%寬度元素的更新大小

我有這個頁面結構:

<body> 
    <nav></nav> // position absolute, width 300px 
    <main></main> // position relative, width 100% 
</body> 

Layout

主要元素奠定了淨資產值。我有一個jquery函數來打開將主體推向右側的導航。但主要因素是走出我的身體無處不在,而不是保持100%的寬度。這非常合乎邏輯,因爲身體沒有改變。

我怎樣才能構建我的佈局,以實現主要元素響應變化的行爲?

這裏是的jsfiddle:

http://jsfiddle.net/9td4cf03/

+3

你能否提供jsfiddle代碼示例? – ummahusla 2014-10-10 11:49:40

+0

當您打開導航時,您可以將導航寬度減去主寬度。 – 2014-10-10 11:54:33

+1

[Expand div to take remaining width]可能的重複(http://stackoverflow.com/questions/1260122/expand-div-to-take-remaining-width) – Nit 2014-10-10 11:56:26

回答

2

我把簡化了您的HTML和CSS如下的自由。

一種方法是使用絕對定位將nav塊及其內容移出 流。

.st-main塊堆積在nav上。

單擊按鈕時,可以通過展開 .st-main塊的左邊距使nav可見。這對CSS3轉換非常有效。

$(document).ready(function() { 
 
    $("button").on('click', function() { 
 
     $(".st-main").toggleClass('expand'); 
 
    }); 
 
});
html, body { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0; 
 
} 
 
.st-container { 
 
    height: 100%; 
 
    position: relative; 
 
} 
 
.st-menu { 
 
    position: absolute; 
 
    top: 0; left: 0; 
 
    width: 300px; 
 
    height: 100%; 
 
    background-color: beige; 
 
} 
 
.st-main { 
 
    position: relative; 
 
    z-index: 1; 
 
    height: 100%; 
 
    margin-left: 0px; 
 
    transition: margin-left 0.5s ease-in-out; 
 
    background-color: lightgray; 
 
    border: 1px dotted blue; 
 
    box-sizing: border-box; 
 
} 
 
.st-main.expand { 
 
    margin-left: 300px; 
 
} 
 
button { 
 
    position: absolute; 
 
    z-index: 2; 
 
    top: 0; left: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="st-container"> 
 
    <button>Click</button> 
 
    <nav class="st-menu"> 
 
     <ul id="menu"> 
 
      <li>First stuff</li> 
 
      <li>Second stuff</li> 
 
      <li>Third stuff</li> 
 
     </ul> 
 
    </nav> 
 
    <main class="st-main"></main> 
 
</div>

+0

謝謝!這是完美的,很容易。 :) – 2014-10-13 06:58:50

0

一種方法是你的主要元素上使用box-sizing(或可能的一切)。這將使padding值包含在整體width值中。實際上它會允許你給它一個width:100%;,然後給它一個padding-left:300px;,並且從100%中減去300px。

CSS:

*, 
*:before, 
*:after { /* apply a natural box layout model to all elements; see http://www.paulirish.com/2012/box-sizing-border-box-ftw/ */ 
    -webkit-box-sizing: border-box; /* Not needed for modern webkit but still used by Blackberry Browser 7.0; see http://caniuse.com/#search=box-sizing */ 
    -moz-box-sizing: border-box; /* Still needed for Firefox 28; see http://caniuse.com/#search=box-sizing */ 
    box-sizing:   border-box; 
} 

您可以通過*這適用於一切都像我證明,或者只是把它應用到主。如果你的網站不復雜,我建議將它應用於一切。