转自: http://blog.onlygrape.com/float-position/271
在进行CSS网页布局时,对元素与容器进行布置与规划,最常用的两个属性就是浮动float和定位position。这两个属性的理解对CSS网页布局的学习非常重要。
首先了解float(浮动)和position(定位)属性的基础知识:
float(浮动)属性:
float:none|left|right
取值:
none: 默认值。对象不飘浮
left: 文本流向对象的右边
right: 文本流向对象的左边
float(浮动)属性的一个实例(一行两列):
xhtml代码:
< div id =”column1″ > 这里是第一列 </ div >
< div id =”column2″ > 这里是第二列 </ div >
< div class =”clear” ></ div > <! –元素需要清除浮动 但可能与Web标准意图相背– >
</ div >
CSS代码:
#column1 { float : left ; width : 40px ; }
#column2 { float : right ; width : 60px ; }
.clear { clear : both ; }
position(定位)属性:
position:static|absolute|fixed|relative
取值:
static: 默认值。无特殊定位,对象遵循HTML定位规则
absolute: 将对象从文档流中拖出,使用left,right,top,bottom等属性
相对于其最接近的一个最有定位设置的父对象进行绝对定位。
如果不存在这样的父对象,则依据body对象。而其层叠通过z-index属性定义
fixed: 未支持。对象定位遵从绝对(absolute)方式。但是要遵守一些规范
relative: 对象不可层叠,但将依据left,right,top,bottom等属性在正常文档流中偏移位置
position(定位)属性的一个实例(一行两列):
xhtml代码:
< div id =”column1″ > 这里是第一列 </ div >
< div id =”column2″ > 这里是第二列 </ div >
</ div >
css代码:
#column1 { position : absolute ; top : 0 ; left : 0 ; width : 200px ; }
#column2 { position : absolute ; top : 0 ; right : 0 ; width : 100px ; }
float(浮动)和position(定位)属性的区别
显然,float是相对定位的,会随着浏览器的大小和分辨率的变化而改变,而position就不行了,所以一般情况下还是float布局!在局部可能会用到position进行定位!
查看一些float(浮动)和position(定位)的CSS布局实例:
单行一列
#content { margin : 0 auto ; width : 400px ; }
两行一列
#content-top { margin : 0 auto ; width : 400px ; }
#content-end { margin : 0 auto ; width : 400px ; }
三行一列
#content-top { margin : 0 auto ; width : 400px ; }
#content-mid { margin : 0 auto ; width : 400px ; }
#content-end { margin : 0 auto ; width : 400px ; }
单行两列
#bodycenter#dv1 { float : left ; width : 280px ; }
#bodycenter#dv2 { float : right ; width : 420px ; }
两行两列
#bodycenter { width : 700px ; margin : 0 auto ; overflow : auto ; }
#bodycenter#dv1 { float : left ; width : 280px ; }
#bodycenter#dv2 { float : right ; width : 420px ; }
三行两列
#bodycenter { width : 700px ; margin : 0 auto ; }
#bodycenter#dv1 { float : left ; width : 280px ; }
#bodycenter#dv2 { float : right ; width : 420px ; }
#footer { width : 700px ; margin : 0 auto ; overflow : auto ; clear : both ; }
单行三列(绝对定位)
#middle { margin : 0 120px 0 120px ; }
#right { position : absolute ; top : 0 ; right : 0 ; width : 120px ; }
float定位
xhtml代码:
< div id =”column” >
< div id =”column1″ > 这里是第一列 </ div >
< div id =”column2″ > 这里是第二列 </ div >
< div class =”clear” ></ div > <! –元素需要清除浮动 但可能与Web标准意图相背– >
</ div >
< divid =”column3″ > 这里是第三列 </ div >
< divclass =”clear” ></ div > <! –元素需要清除浮动 但可能与Web标准意图相背– >
</ div >
css代码:
#column { float : left ; width : 200px ; }
#column1 { float : left ; width : 120px ; }
#column2 { float : right ; width : 80px ; }
#column3 { float : right ; width : 100px ; }
.clear { clear : both ; }