Html CSS - 使 div 消耗所有可用空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5776367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS - Making a div consume all available space
提问by Kayote
All,
全部,
I have a page which is suppose to take up only the available screen space in the browser.
我有一个页面,假设它只占用浏览器中的可用屏幕空间。
I have a 'top bar' and a 'bottom bar', both of which are fixed positioned at the top and bottom of the page. I want to have a div which will consume (take up) the remaining of the space inbetween the two bars mentioned above.
我有一个“顶栏”和一个“底栏”,它们都固定在页面的顶部和底部。我想要一个 div 来消耗(占用)上面提到的两个条之间的剩余空间。
Its crucial that the middle div is not overlapped by the top and bottom bars. Is this at all possible with CSS or do I need to make use of js.
中间 div 不与顶部和底部条重叠,这一点至关重要。这完全可以使用 CSS 还是我需要使用 js。
Also, if I do go with js, considering the browser loads up the CSS first before the js code, how is the above work out using js for centre positioning?
另外,如果我确实使用 js,考虑到浏览器会在 js 代码之前先加载 CSS,那么使用 js 进行中心定位如何解决上述问题?
Many thanks,
非常感谢,
回答by Sotiris
You can use relative
and absolute
positions. Here an example:
您可以使用relative
和absolute
位置。这里有一个例子:
css
css
html,body,#wrapper {
height:100%;
margin:0;
padding:0;
}
#wrapper {
position:relative;
}
#top, #middle, #bottom {
position:absolute;
}
#top {
height:50px;
width:100%;
background:grey;
}
#middle {
top:50px;
bottom:50px;
width:100%;
background:black;
}
#bottom {
bottom:0;
height:50px;
width:100%;
background:grey;
}
html
html
<div id="wrapper">
<div id="top"></div>
<div id="middle"></div>
<div id="bottom"></div>
</div>
回答by andyb
回答by Stephen Chung
Use absolute positioning on the body
tag. position:absolute
with zero top and bottom will "stretch" body to be the same size as the browser window. Alternatively, setting height: 100%
also works but I remember it works wierd for certain old browsers.
在body
标签上使用绝对定位。position:absolute
顶部和底部为零将“拉伸”主体到与浏览器窗口相同的大小。或者,设置height: 100%
也有效,但我记得它在某些旧浏览器上很奇怪。
Then use absolute positioning on the center div, with enough top/bottom offsets to avoid your header and footer bars. The header bar is absolutely positioned with top
and the fotter is absolutely positioned with bottom
.
然后在中心 div 上使用绝对定位,并使用足够的顶部/底部偏移量来避开页眉和页脚栏。标题栏绝对定位于top
,而 fotter 绝对定位于bottom
。
Note: This won't work on mobile browsers. You'll need to use JS to get the window's height and manually set the center div's height.
注意:这不适用于移动浏览器。您需要使用 JS 来获取窗口的高度并手动设置中心 div 的高度。