float居中

1 float居中

<html>
<head>
    <title>居中的菜单</title>
    <style type="text/css">
       .a1 {width:500px;position:relative;background:#ddd;height:50px;}     //定义宽度,提供参考系
       .a2 {float:left;position:relative;left:50%;background:#f00;height:40px;}    //左偏移父容器50%(250px),浮动后a2的宽度是根据内容决定,而不是父容器决定,此时a2的宽度为360px
       .a3 {float:left;position:relative;left:-50%;height:30px;background:#00f;}   //根据父容器(a2)的宽度左偏移50%(180px)
    </style>
</head>
<body style="text-align:center">
    <div class="a1">
       <div class="a2">
            <div class="a3">111111111111111</div>
            <div class="a3">222222222222222</div>
            <div class="a3">333333333333333</div>
            <div style="clear:both"></div>
       </div>
    </div>
</body>
</html>

2 垂直居中

<html>
<head>
    <title>居中的菜单</title>
    <style type="text/css">
       .a1 {position:relative;height:200px;background:#333;width:500px;}     //高度,参考系
       .a2 {position:relative;top:50%;background:#888;width:450px;}            //高度自适应了,此时a2的高度为82px,上偏移100px
       .a3 {position:relative;top:-50%;background:#eee;width:400px;}           //返回去82px*50%=41px,高度居中
    </style>
</head>
<body style="text-align:center">
    <div class="a1">
       <div class="a2">
            <div class="a3">1111111<br>11111111<br>11111111<br>11111111</div>
       </div>
    </div>
</body>
</html>

 

总结:关键在于理解relative和float的定位方式

1 relative针对的是上一个dom对象的位置,left(right,top,bottom)采用百分比时的被乘数都是上一个dom对象的长宽

2 直接使用relative,即前dom对象或父dom对象都未设置position属性

          如果在容器内,按照容器的左上角计算

          在容器外,按照上任意一个容器的下方计算top,按照body计算left

2 如果不采用float方式,宽度为100%,采用了float,宽度为自适应

posted @ 2014-05-13 14:34  风林火山09  阅读(436)  评论(0编辑  收藏  举报