单列布局、两列布局、三列布局

一、        单列布局

HTML 代码:

 1 <div id="header">
 2         <h2>Page Header</h2>           
 3             <p>头部内容</p>
 4 </div>
 5  <div id="content">
 6     <h2>Page Content</h2>
 7         <p>正文内容</p>        
 8 </div>
 9 <div id="footer">    
10        <h2>Page Footer</h2>
11        <p>底部内容</p>
12 </div>>

1.1、定宽

思路:设置div的左右margin为auto

#header,#footer,#content{
            margin:0 auto;
            width:800px;
            margin-top: 10px;
        }

1.2、变宽

思路设置宽度为相对宽度,常用百分比

#header,#footer,#content{
        margin:0 auto;
        width:70%;
        margin-top: 10px;
    }

二、        两列布局

HTML结构:

<div id="header">
        <h2>Page Header</h2>          
        <p>头部内容</p>
 </div>
<div id="container">
     <div id="content">
           <h2>Page Content</h2>
            <p>正文内容</p>
     </div>
     <div id="side">
            <h2>Page Content</h2>
            <p>侧边栏内容</p>
      </div>
</div>
  <div id="footer">   
        <h2>Page Footer</h2>
        <p>底部内容</p>
   </div>>

2.1、两列固宽

方法一:绝对定位法: 使content相对于container绝对定位,脱离文档流,side就会向上移动占据原来content所在的位置,然后将content的宽度和side的左margin设置为相同的值,就正好可以保证它们并列紧挨着放置,且不会相互重叠。

#container{
     position: relative;
}
 
 #content{
            border: 2px solid #00f;
            position: absolute;
            top: 0;
            left: 0;
            width: 500px;
         }
  
 #side{
            border: 2px solid #f90;
             margin: 0 0 0 500px;
         }

缺点:当右边的side比左边的content高时,显示效果不会有问题,但是如果左边的content比右边的side高的话,由于content已经脱离了文档流,对包裹的container这个div的高度不会产生影响,而footer是根据side栏确定的,content栏会遮蔽部分甚至全部footer栏。

方法二、浮动法将content和side都设置为向左浮动,二者的宽度等于总宽度。

#content{      
   float: left;
   width: 500px;
   border: 2px solid #00f;
}
 
#side{
    float: left;
    width: 300px;
  border: 2px solid #f90;
  }

此时footer的位置不太正常。container的边框也被缩成一条线,需要清除浮动对于包裹元素高度的影响。应用.clearfix(前面布局模型章节中写过)

2.2、两列等比例变宽

方法一、绝对定位法:同上面的两列固宽,不同的是使用百分比宽度和边距,container等外层宽度相对浏览器窗口,content和side相对于外层div定义宽度。

方法二、浮动法:同上面的浮动法,将width的值改为百分比。

2.3、两列单列变宽

方法一、绝对定位法:

#header,#footer,#container {
            margin: 10px auto;
            width: 85%;
        }
 #container {
            position: relative;
        }
 
  #side {  /*定宽*/
             position: absolute;
            top: 0;right: 0;
             width: 300px;
            border: 2px solid #f90;
         }
 
   #content {/*变宽*/
             margin: 0 300px 0 0;
             border: 2px solid #00f;
        }

所以使用这种方法时要注意保证变宽列的高度是最高的。使固定宽度列绝对定位。

方法二、浮动法:同上面的浮动法

三、     三列布局

3.1、三列定宽

方法1:绝对定位法:原理同两列布局,只不过需要设置content的左右margin

方法2:浮动法:原理同两列布局

 

3.2、三列等比例变宽

绝对定位法和浮动法

同上面的两列等比例变宽,只要分配好每一列百分比就好

3.3、中间列定宽,两列变宽

绝对定位法和浮动法

3.4、中间列变宽,两列定宽

见双飞翼布局和圣杯布局一篇。

原文地址:https://www.cnblogs.com/jiayuexuan/p/7240156.html