您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

CSS单列布局以固定宽度为中心的宽度固定为100%,带页眉和页脚

CSS单列布局以固定宽度为中心的宽度固定为100%,带页眉和页脚

针对现代浏览器(2015)的简单方法,使用display:flex

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>

使用边界框,因此将与较旧的浏览器不兼容(并且您可能需要添加moz,webkit和ms前缀才能使其在所有浏览器中都能正常工作):

html,
body { height: 100%; margin: 0; padding: 0; }
#wrapper { padding: 100px 0 75px 0; height: 100%; @R_45_2419@-sizing: border-@R_45_2419@; }
.middle { min-height: 100%; position: relative; }
.top { margin-top: -100px; height: 100px; }
.bottom { margin-bottom: -75px; height: 75px; }
.container { padding: 10px; }

使用绝对定位,并且对跨浏览器更友好:

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;}

略微更改了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;}
CSS 2022/1/1 18:17:48 有600人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶