两种布局方式float和position

来源:互联网 发布:集装箱运输软件 编辑:程序博客网 时间:2024/06/17 23:51

对于在网页模块布局时,经常会出现多个模块并列的情况,也就是混合布局。一般处理上、中、下结构,中间多个模块并列的情况,要用到float或者position。以下具体举例。

1.使用float来布局

嵌套三列并列:其结构为上,左,右(左右),下

实现思路:左模块,float:left;右大模块里,左右模块都浮动。在foot模块,清除浮动(clear:both;或者width:100%,overflow:hidden;)具体代码如下:

CSS代码:

<span style="font-size:14px;">/*1.宽度用px数字衡量*/body{ margin:0; padding:0;}div{ text-align:center; font:bold 14px Arial, Helvetica, sans-serif;}.head{ height:80px; background-color:#9C3;}.left{ background-color:#99C; height:500px; width:300px;  float:left;}.main{ background-color:#CCC; width:945px; float:right;}.middle{ width:345px; background-color:#903; height:500px; float:left;}.right{  width:600px; background-color:#9F0; height:500px; float:right;}.foot{width:100%; overflow:hidden;background-color:#96C; height:80px;}</span>
HTML代码:
<span style="font-size:14px;"><div class="head">头部</div><div class="left">左边</div><div class="main">    <div class="middle">r_Left</div>    <div class="right">r_right</div></div><div class="foot">尾部</div></span>

非嵌套三列并列:中部的三模块,左模块float:left;右模块float:right;剩余的中间模块,利用float会对紧邻的下一模块产生影响的特性,在HTML文档中,将中间模块放到左,右,模块之后。按照文档流执行顺序,中间模块最后执行,会因为float影响上浮。此时,只需控制好margin。(因此不需要再清除浮动)

CSS代码:

<span style="font-size:14px;">/*2.宽度用百分比衡衡量*/.test_Head{ height:50px; background-color:#F30;}.test_Left{ height:100px; width:20%; background-color:#F3C; float:left;}.test_Center{ height:100px; margin:0 20%; background-color:#3CF;}.test_Right{ height:100px; width:20%; background-color:#9F3;float:right;}.test_Foot{  clear:both;height:50px; background-color:#933;}</span>
HTML代码:

<div class="test_Head">这是百分比测试</div><div class="test_Left">这是百分左部</div><div class="test_Right">百分比的右部</div><!--注意顺序,必须先左模块左浮动,右模块右浮动,再放中间模块,放margin:0 %20;否则的话,,,,,右模块不会再同一高度--><div class="test_Center">百分比的中部</div><div class="test_Foot">这是百分比尾部</div>


2.使用position:absolute

position绝对定位可用于多种情况,不管是大的布局,还是模块内或者模块间位置的布置。此处举例左右两边固定,中间自适应的布局情况。

思路分析:

左右固定,即position:absolute,定坐标(top:xx  px; left: xx  px;)

中间自适应,即设置左右宽度,中间宽度不设置,随着窗口大小的改变,中间宽度自由变化。因为绝对定位脱离了文档流,所以中间模块布局 margin: 0 xx (right-width) px  0  xx(left-width)px;


CSS代码:

<span style="font-size:14px;">/* 1.绝对定位(position:absoulte;位置信息),适用于 一些模块需要固定位置,使用position定位的都不在标准文档流当中现为:-------左右固定,中间自适应 */ body{margin:0; padding:0;}div{font-weight:bold; text-align:center;}.head{ height:100px; background-color:#CF9;}.left{ height:500px; background-color:#C66; width:30%; position:absolute; top:100px; left:0;}/*如果不使用float,多个模块并列必须使用:position绝对定位加上 margin属性*/.middle{height:500px;background-color:#C30; margin:0 20% 0 30%;;}/*使用position绝对定位的特点:脱离文档流;*/.right{ height:500px; width:20%; background-color:#03C; position:absolute; top:100px; right:0;}.foot{border:#000 medium dashed; height:80px; background-color:#CCC};</span>

HTML代码:

<div><div class="head">头部</div><div class="left">左边</div><div class="middle">中部</div><div class="right">右边</div><div class="foot">尾部</div></div>


0 0
原创粉丝点击