2017-06-03 78 views
-1

如果你有一个是这样的HTML文档:有没有CSS高度:休息属性?

<body> 
    <div id="top"></div> 
    <div id="rest"></div> 
</body> 

,我给“顶”的div 40像素的高度,是有办法让“休息” div的高度的其余部分身体在CSS。我知道这是可能在Javascript中这样

function derest(){ 
var bodyheight = window.getComputedStyle(document.getElementsByTagName('body')[0], null).height; 

bodyheight = bodyheight.substring(0, bodyheight.length - 2); 

var topheight = window.getComputedStyle(document.getElementById('top'), null).height; 

topheight = topheight.substring(0, topheight.length - 2); 

restheight = bodyheight - topheight; 

document.getElementById("rest").style.height = restheight; 

} 

但是这需要花费大量的时间,所以有没有更好的方式来做到这一点?

+2

这是可能的Flexbox的。 (更具体地说'flex-grow:1')。有一个很好的谷歌搜索。 –

回答

1

你可以只使用纯CSS

#top{ 
    height:40px; 
    background:green; 
} 
#rest{ 
    height:calc(100% - 40px); 
    background:red; 
} 
body,html{ 
    height:100%; 
    margin:0; 
    padding:0; 
} 
-1

您可以使用:

#top { 
position: fixed; 
left: 0px; 
top: 0px; 
width: 100%; 
height: 40px; 
} 

#rest { 
position: fixed; 
top: 40px; 
left: 0px; 
width: 100%; 
height: calc(100% - 40px); 
} 

甚至使用填充顶部40像素,而不是进行固定的#rest DIV

https://jsfiddle.net/lonking/L5mwd6r5/

+0

为什么downvote没有理由?有用 – Diego

0

您可以使用flex来允许#rest伸展填写身高:

html { 
 
    height: 100%; 
 
    margin:0; 
 
    padding:0; 
 
} 
 
body { 
 
    height: 100%; 
 
    margin:0; 
 
    padding:0; 
 
    display: flex; 
 
    flex-direction: column 
 
} 
 
#top { 
 
    height: 40px; 
 
    background: red; 
 
} 
 
#rest { 
 
    flex: 1 1 auto; 
 
    background: blue; 
 
}
<div id="top"></div> 
 
<div id="rest"></div>

0

如果容器是display: flex那么你可以设置一个元素增长(与flex-grow)填补剩余空间。

html, 
 
body { 
 
    min-height: 100vh; 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
body { 
 
    display: flex; 
 
    flex-direction: column; 
 
} 
 

 
header { 
 
    background-color: #aaf; 
 
} 
 

 
main { 
 
    background-color: #afa; 
 
    flex: 1 0 auto; 
 
} 
 

 
footer { 
 
    background-color: #faa; 
 
}
<header> 
 
    Header 
 
</header> 
 
<main> 
 
    Main 
 
</main> 
 
<footer> 
 
    Footer 
 
</footer>