最近在重构web导航的时候就发现一个问题,如何实现顶部固定,中部自适应的布局。
很多人会认为这很简单啊,顶部使用position: fixed;就可以实现。
<!DOCTYPE html> <html lang="zh"><head><meta charset="UTF-8"><title>顶部固定,中部自适应</title><style type="text/css">* {margin: 0;padding: 0;}.hd {position: fixed;z-index: 99;top: 0;width: 100%;height: 20px;padding: 15px 0;text-align: center;color: #fff;background: #f00;}.bd {width: 100%;margin-top: 50px;padding: 15px 0;text-align: center;color: #fff;background: #00f;}</style> </head><body><header class="hd">我是固定头部</header><div class="bd">我是中部部分<p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p></div> </body></html>
这种做法确实简单,但是,请看清题目,顶部固定,中部自适应。(顶部不包括滚动条)
花了一点时间的思考,终于想出来了,中部使用position:absolute;就可以实现。
<!DOCTYPE html> <html lang="zh"><head><meta charset="UTF-8"><title>顶部固定,中部自适应</title><style type="text/css">* {margin: 0;padding: 0;}.hd {width: 100%;height: 50px;padding: 15px 0;text-align: center;color: #fff;background: #f00;}.bd {position: absolute;top: 50px;/* 往下移顶部的距离 */bottom: 0;/* 底部贴边 */overflow: auto;/* 溢出的部分自适应 *//* 不设置高度 */width: 100%;padding: 15px 0;text-align: center;color: #fff;background: #00f;}</style> </head><body><header class="hd">我是固定头部</header><div class="bd">我是中部部分<p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p><p>超出的部分滚动</p></div> </body></html>
PS:这种做法的好处是不占顶部宽度,顶部100%显示全部区域,特别适用于针对右上角有菜单导航的页面。