之前写过一个小项目,首先这个页面布局是这个样子滴,举个栗子,京东的首页:
这算是一种还算常见的页面样式吧,头部和底部固定(或者底部固定没有头、头部固定没有底),有的会用fixed去做,但有在很多手机上会出现很多的奇葩的问题。
思前想后,后来我决定使用弹性布局去做,至少在手机浏览器中都是支持的,虽然写法上可能为了考虑老版本要多谢一些兼容性的无用CSS,配合HTML5 history API还可以实现一个无刷新跳转,并且用户可点击前进后退和刷新页面。最近有遇到一个开发需求:单个H5页面,于是乎我干脆把之前写的小项目的CSS+HTML布局单拎出来,方便以后使用,其实实现方法很无聊很弱智:
首先是整个页面的骨架(HTML部分):
<body> <section class="page"> <header class="header"> 我是头部 </header> <section class="content"> <div>asdasd</div> </section> <footer class="footer"> <nav class="foot-nav"> <b>首页</b> <b>其他</b> <b>中心</b> </nav> </footer> </section> </body>
很简单,就是一个头(.header)、内容区(.content)、脚部(.footer),然后被一个.page包裹就实现了满屏,骨架超简单,在附上CSS实现:
/*清除手机的一些基本样式*/ html { font-size:62.5%; width:100%; height:100%; -webkit-font-smoothing:antialiased; } body { text-align:center; -webkit-user-select:none; width:100%; height:100%; /*background:#fff;*/ /*默认背景颜色*/ /*font-size:1.2rem;*/ /*默认字体大小*/ /*color: #000;*/ /*默认字体颜色*/ font-family:"Microsoft YaHei","Helvetica Neue",Helvetica,STHeiTi,sans-serif; -webkit-text-size-adjust:none; } * { margin:0; padding:0; list-style:none; } i, em, b { font-style:normal; font-weight:normal; } :-moz-placeholder {color:#ccc;} ::-moz-placeholder {color:#ccc;} ::-webkit-textarea-placeholder {color:#ccc;} :-ms-textarea-placeholder {color:#ccc;} img{ width:100%; vertical-align:top; } input,textarea,select{ -webkit-appearance:none; font-size:1.2rem; border:0; background:transparent; font-family:"黑体","Microsoft YaHei","Helvetica Neue",Helvetica,STHeiTi,sans-serif; outline:none; } input,a,span{ -webkit-tap-highlight-color: rgba(0,0,0,0); } /*flex最外框*/ .page{ display:-webkit-box; -webkit-box-orient:vertical; height:100%; } /*flex内容区*/ .page .content{ position:relative; -webkit-box-flex:1; -webkit-flex:1; flex:1; overflow:auto; -webkit-overflow-scrolling:touch; background-color:#ccc; } /*flex头部*/ .header{ display: -webkit-box; } .header *{ display: block; } /*flex底部,按钮平均分布*/ .footer{ overflow: hidden; background:#fff; } .foot-nav{ display:-webkit-box; height: 2rem; line-height: 2rem; } .foot-nav *{ display: block; -webkit-box-flex: 1; -webkit-flex:1; flex:1; }
就是上面一段CSS,就会被浏览器解析成这样:
头部和底部都是被子元素撑开的,并不用指定高度,,底部的button不管来几个也都是平均分布的,完全不用去计算一堆margin、padding以及position等等,弹性布局超赞有木有,当年的CSS2+HTML4时代要想实现这样的布局超麻烦有木有
然后再来个弹出层,一个简单的基于头尾固定的H5小页面就出来了:
<div class="layer-wraper"> <div class="layer-inside"> 哈哈哈哈哈居中居中 <p>呜呜呜呜</p> </div> </div>
/*弹出层样式(自动居中)*/ .layer-wraper{ position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,255,0,0.7); display:table; width:100%; height:100%; z-index:1000; } .layer-inside{ display:table-cell; vertical-align:middle; }
使用table布局自动居中,并且这时使用fixed充满屏幕(百分比情况下fixed还算可靠),这样一个绿色的半透明背景并且自动居中的弹出层基本样式救出来了:
弹性布局大法好,应付一般的页面都不是问题,除非设计的脑子被僵尸吃了,硬要一些变态的需求以及狗shit一样的设计