前端页面布局经验谈





王海洋

wanghaiyang@hujiang.com

页面布局六点小经验

  • 浮动布局及先后顺序
  • 清除浮动的方式
  • position: absolute;的使用
  • 动态Add CSS Rule
  • 竖向垂直百分比定位
  • 不同fontSize文字横向对齐

1. 浮动布局及先后顺序        

  • 居左(右)布局
    - 全部 float:left; 或 float:right;
  • 左右布局
    - float:left; 加 float:right; 或 float:right; 加 float:left;
  • 左中右布局
    - float:right; 加 default 加 float:left;
    注:左在右前的方式会出现错位!! demo

2. 清除浮动的方式        

  1. clear:both;
  2. :after && zoom
  3. overflow: not visible
  4. float;
demo

标准清除浮动方式 clearfix        

<style type="text/css">
.clearfix{*zoom:1}
.clearfix:after{display:table;content:" ";clear:both;}
hr.clearfix {font-size: 1px; line-height: 1px; height: 1px; overflow: hidden; clear: both; border: 0px; padding: 0px; margin: -1px 0px 0px 0px; list-style: none; border-style: none; background: none; visibility: hidden;}
</style>

3. position: absolute;的使用        

  • 不设置 left/right 会怎么样 ?
    - 使用margin调整位置
  • 一直用 left, top ?
    - left/right和top/bottom可以随意组合
  • 同时设置 left/right 会怎么样 ?
    - 都会生效
  • 同时设置 left/right、top/bottom 和 width/height ?
    - right, bottom 值会无效
demo

4. 动态Add CSS Rule        

  • 无需操作DOM
  • 动态操作批量元素
  • 便于撤销和恢复
  • 浏览器差异
    - createElement('style') / createStyleSheet()


importCssString.htmlimportCssString2.htmlimportCssString3.html  

5. 竖向垂直百分比定位        

  • 坑爹的 margin-top: 20%; 是以宽为基数
  • IE7+ 可以使用 position: fixed; top: 20%;
  • IE6,7 可以用 expression 或 setExpression


demo1, demo2

6. 不同fontSize文字横向对齐        

  • vertical-align: top;无效效
  • 使用float加margin-top


demo

「Thanks」