2016-08-09 120 views
0

我試圖完成一些非常簡單的事情。我可憐的生鏽的CSS技能並沒有幫助。CSS拉伸至100%高度

這是要實現: enter image description here

我不能做到這一點。如果我使用height: 100%,它在沒有太多文本的情況下工作,但是當我添加大量Lorem Ipsum時,內容div會被拉伸,左邊的菜單div不會隨之縮放。

我不想使用JavaScript,只是乾淨的CSS,如果這是可能的。

HTML:

<html> 
<head> 
<title>test</title> 
<link rel="stylesheet" type="text/css" href="css/style.css"> 
</head> 
<body> 
<div id="header">Header</div> 
<div id="menu">Menu</div> 
<div id="content">Content (paste a lot of lorem ipsum here and menu doesn't stretch)</div> 
</body> 
</html> 

CSS

body 
{ 
    margin: 0; 
    height: 100%; 
    background-color: gray; 
} 
#header 
{ 
    height: 50px; 
    background-color: white; 
    border: 1px solid black; 
} 
#menu 
{ 
    width: 225px; 
    float: left; 
    height: calc(100% - 50px); 
    background-color: white; 
    border: 1px solid black; 
} 
#content 
{ 
    overflow: auto; 
    background-color: white; 
    border: 1px solid black; 
} 
+1

柔性盒是你在找什麼。 - https://css-tricks.com/snippets/css/a-guide-to-flexbox/ – Andrew

+1

它實際上並不像您想象的那麼簡單,而且這是很多人提出的常見設計要求,那不是直接的或「開箱即用' – Lee

+0

你想要的外觀**看起來很簡單**,但不是。你問了很多瀏覽器。而且,身高100%並不符合你的想法:http://stackoverflow.com/questions/7880365/why-does-100-not-mean-100-height。最後,你不需要100% - 你想100%*減去你的標題*的高度。 –

回答

3

Flexbox,就可以做到這一點。

Codepen Demo

* { 
 
    margin: 0; 
 
    padding: 0; 
 
    box-sizing: border-box; 
 
} 
 
html { 
 
    height: 100%; 
 
} 
 
body { 
 
    min-height: 100%; 
 
    display: flex; 
 
    flex-direction: column; 
 
} 
 
header { 
 
    height: 50px; 
 
    background: #bada55; 
 
} 
 
section { 
 
    display: flex; 
 
    flex: 1; 
 
    background: #c0ffee; 
 
} 
 
aside { 
 
    width: 150px; 
 
    background: darkgoldenrod; 
 
} 
 
main { 
 
    min-height: 100%; 
 
    /*height: 2000px;*/ /* uncomment this to see difference */ 
 
    background: blue; 
 
    flex: 1; 
 
}
<header></header> 
 
<section> 
 
    <aside></aside> 
 
    <main></main> 
 
</section>

+0

這將總是延伸到瀏覽器窗口的底部? –

+0

是的。嘗試一下。請注意,我沒有在sicebar上設置高度,或者主內容不是「min-height:100%」。側欄總是調整到主要部分的高度。 –

+0

應該指出的是,這個代碼示例不包含它們,但可能推薦使用所有的供應商前綴。根據我的經驗,它會變得冗長,但具有良好的瀏覽器支持*除非您關心IE9 *:http://caniuse.com/#search=flex –

0

試舉高度相對於視口的高度。 VH

height:100vh; 
+0

這是否工作?你有一個演示它的小提琴嗎?如果是這樣,這是一個很好的解決方案。它如何容納標題空間? –

+0

檢查出來.. https://jsfiddle.net/kysaws32/ – Abhishek

+1

有很多內容這不起作用 - https://jsfiddle.net/kysaws32/1/ –