我最近一直在研究一种 CSS 布局,它将显示一个固定宽度(最小宽度,最好可扩展)的居中列,该列占据整个高度(减去页眉和页脚)。
对此有什么建议吗?我已经尝试了这里发布的几种方法,但没有一种符合我的标准。另外,我不想为此使用 JS,所以它必须是纯 CSS。
我不是专家,所以我不知道该采取哪种方法:
三列,每侧列边距减去中心列宽度的一半,以及一个人造中心列以拉伸(stretch)到 100% 高度?我有点不喜欢这个想法,因为我的侧栏将没有任何内容
单列边距 0 auto 0 auto 将其居中并顶部:xx px 为标题腾出空间?那么如何将它拉伸(stretch)到 100% 高度呢?
非常感谢任何帮助。
干杯, 交叉
最佳答案
更新
使用 display:flex
为现代浏览器 (2015) 执行此操作的简单方法:
html,
body {height:100%; padding:0; margin:0; width:100%;}
body {display:flex; flex-direction:column;}
#main {flex-grow:1;}
/* optional */
header {min-height:50px; background:green;}
#main {background:red;}
footer {min-height:50px; background:blue;}
<header>header</header>
<div id="main" role="main">content</div>
<footer>footer</footer>
以上内容允许固定高度的页眉和页脚(只需向样式添加高度)以及可变高度(如当前所示 - 可以根据页眉和页脚的内容更改),内容占据其余部分的空间。
如果内容比文档长,页脚会被下推。
旧帖:
有几种方法可以用纯 css 来做到这一点。基本上你需要从这样的 html 结构开始:
<div id="wrapper">
<div class="top"></div>
<div class="middle">
<div class="container">
</div>
</div>
<div class="bottom"></div>
</div>
版本 1 使用边框框,因此与旧版浏览器不兼容(您可能需要添加 moz、webkit 和 ms 前缀才能使其在所有浏览器中运行):
html,
body { height: 100%; margin: 0; padding: 0; }
#wrapper { padding: 100px 0 75px 0; height: 100%; box-sizing: border-box; }
.middle { min-height: 100%; position: relative; }
.top { margin-top: -100px; height: 100px; }
.bottom { margin-bottom: -75px; height: 75px; }
.container { padding: 10px; }
Version 1
Version 1 with content
Version 1 centred column
版本 2 使用绝对定位并且对跨浏览器更友好:
html,
body {min-height:100%; padding:0; margin:0;}
#wrapper {padding:50px 0; position:absolute; top:0; bottom:0; left:0; right:0;}
.middle {min-height:100%;}
.top {margin-top:-50px; height:50px;}
.bottom {margin-bottom:-50px; height:50px;}
.container {padding:10px;}
Version 2
Version 2 with content
Version 2 centred column
版本 3 稍微更改了 html,但如果您具有可变高度的页眉和页脚,则更加健壮:
<div id="wrapper">
<div class="table">
<div class="top row"><div class="cell"></div></div>
<div class="middle row"><div class="container cell"></div></div>
<div class="bottom row"><div class="cell"></div></div>
</div>
</div>
CSS
html,
body {min-height:100%; padding:0; margin:0;}
#wrapper {position:absolute; top:0; bottom:0; left:0; right:0;}
.table {display:table; width:100%; height:100%;}
.row {display:table-row;}
.cell {display:table-cell;}
.middle {height:100%;}
.container {padding:10px;}
Version 3
Version 3 with different height header and footer
Version 3 with content
Version 3 centred column
关于html - CSS 单列布局居中固定宽度 100% 高度带页眉和页脚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23651942/