我有一个简单的页眉、页脚和内容之间的布局,其中每个这样的部分都有未知高度(内容)。目标是让页眉向上,页脚向下,内容居中,仅在需要时显示垂直滚动条。我能够通过下面列出的代码处理页眉、页脚和滚动条,但我找不到如何将内容居中的方法。
这是一个 fiddle : http://jsfiddle.net/mVh44/
>> HTML:
<div id="container">
<div id="header">
<div id="headerText">
header header header
</div>
</div>
<div id="content">
center text here
</div>
<div id="footerPadding">
</div>
<div id="footer">
<div id="footerText">
footer footer footer footer footer footer footer footer footer footer
footer footer footer footer footer footer footer footer footer footer
</div>
</div>
</div>
>> CSS:
html, body {
border: none;
margin: 0;
padding: 0;
background-color: transparent;
font-family: Verdana;
font-size: .9em;
color: black;
height: 100%; /* needed for container min-height */
}
div {
display: block;
overflow: hidden;
}
div#container {
position: relative; /* needed for footer positioning*/
margin: 0 auto; /* center, not in IE5 */
width: 100%;
height: auto !important; /* real browsers */
height: 100%; /* IE6: treaded as min-height*/
min-height: 100%; /* real browsers */
}
div#header, div#footer {
margin: 0;
width: 100%;
}
div#footer {
position: absolute;
bottom: 0; /* stick to bottom */
}
div#headerText, div#footerText {
padding: 1em 0;
text-align: center;
white-space: nowrap;
}
div#headerText {
border-bottom: .5em double gray;
}
div#footerText {
border-top: .5em double gray;
}
>> 脚本:
function myResize() {
$('#footerPadding' ).css('height', $('#footer').css('height'));
}
$(window).resize(function(){
myResize()
});
myResize();
最佳答案
您可以使用 CSS 并更改您的 HTML 标记来做到这一点。
实例:http://jsfiddle.net/mVh44/12/
CSS
#header{
position:absolute;
top:0;
}
div#footer{
position:relative;
display:table-row;
}
#container{
padding: 48px 0 0 0; //48px from the header
display:table;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#content{
display:table-cell;
vertical-align:middle;
height:100%;
}
HTML
<div id="header">
<div id="headerText">header header header</div>
</div>
<div id="container">
<div id="content">
<div class="box">center text here</div>
<div class="box">center text here</div>
</div>
<div id="footer">
<div id="footerText">footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer</div>
</div>
</div>
jQuery
function myResize() {
var headerHeight = $('#header').height();
var windowsWidth = $(window).width();
$('#footerPadding').css('height', $('#footer').css('height'));
$('#container').css('padding-top', headerHeight + 'px');
$('#footerText').css('width', windowsWidth + 'px');
}
关于javascript - 如何使用未知内容和固定布局垂直居中内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20426154/