三种实现左右固定,中间自适应的三栏布局方式

目前为止,我所熟知的左中右三栏宽度自适应于浏览器的方法有三个:绝对定位法margin负值法以及自身浮动法。这些方法简洁实用,且无兼容性问题。css

 


 

1、绝对定位法:左右两栏采用绝对定位,分别固定于页面的左右两侧,中间的主体栏用左右margin值撑开距离。因而实现了三栏自适应布局。html

首先须要三个div,将左右两边的div的position设置为absolute,左右设置为相等固定宽度,在这里设置为200px,而且左边div的top值为0,left值为0,同理右边top值为0,right值为0。而后设置中间div的样式,将中间div的margin-left和margin-right设置为左右两边的固定宽200px。如下是简单的布局:浏览器

 

 

?
1
2
3
4
5
< body >
     < div id="main"></ div >
     < div id="left"></ div >
     < div id="right"></ div >
</ body >

 

下面就是关键的css代码:wordpress

 

?
1
 
?
1
2
3
<style type= "text/css" >
     #main { margin : 0 200px ; background : red ;}
     # left { position : absolute ; top : 0 ; left : 0 ; width : 200px ; background : blue ; height : 100% ;} <br>    # right { position : absolute ; top : 0 ; right : 0 ; width : 200px ; background : green ; height : 100% ;}<br> </style>

这种方式三个div的顺序能够任意改变。布局

此方法的优势在于:理解容易,上手简单,受内部元素影响而破坏布局的几率低,就是比较经得起折腾。
缺点在于:若是中间栏含有最小宽度限制,或是含有宽度的内部元素,当浏览器宽度小到必定程度,会发生层重叠的状况。spa


 

2、自身浮动法:左栏左浮动,右栏右浮动,中间栏放最后。code

如下是布局代码:htm

?
1
 
?
1
2
3
4
5
< body >
     < div id="left"></ div >
     < div id="right"></ div >
     < div id="main"></ div >
</ body > 

下面是css样式代码:blog

 

?
1
2
3
4
5
<style type= "text/css" >
     #main { margin : 0 200px ; background : red ;}
     # left { float : left ; width : 200px ; background : blue ; height : 100% ;}
     # right { float : right ; width : 200px ; background : green ; height : 100% ;}
</style>

这种方式须要注意三个div的顺序,左右两栏的顺序不分前后,可是中间一栏必须放在最后。ci

此方法的优势是:代码足够简洁与高效
缺点是:中间主体存在克星,clear:both属性。若是要使用此方法,需避免明显的clear样式。  


 

3、margin负值法:左右两栏均左浮动,左右两栏采用负的margin值。中间栏被宽度为100%的浮动元素包起来。

下面是布局代码:

?
1
 
?
1
2
3
4
5
6
7
< body >
    < div id="main">
        < div class="content"></ div >
    </ div >
    < div id="left"></ div >
    < div id="right"></ div >
</ body >  

下面是css样式代码:

?
1
2
3
4
5
6
<style type= "text/css" >
    #main { float : left ; width : 100% ;}
    .content { margin : 0 200px ; height : 100% ; background : red ;}
    # left { float : left ; width : 200px ; margin-left : -100% ; background : blue ;}
    # right { float : left ; width : 200px ; margin-left : -200px ; background : green ;}
</style>

左右两栏div的顺序不分前后,可是主体部分div要放前面。

此方法的优势在于:三栏相互关联,可谓真正意义上的自适应,有必定的抗性——布局不易受内部影响。缺点在于:相对比较难理解些,上手不容易,代码相对复杂。出现百分比宽度,过多的负值定位,若是出现布局的bug,排查不易。

相关文章
相关标签/搜索