首页 > 技术文章 > 我学习的三种三栏(左中右)布局方法

zhang-xun 2017-04-25 16:06 原文

我学习的三种三栏(左中右)布局方法(不想要自适应的话设置一个宽度即可)

  1. 绝对定位方法,两边用绝对定位固定在窗口两边,中间采用自适应宽度,利用margin属性把两边撑开。代码如下:

    <style type="text/css">
    
    * {margin: 0;}
    
    .left{position: absolute;top: 0;left: 0;width: 300px;height: 300px;background: #ccc;}
    
    .right{position: absolute;top: 0;right: 0;width: 300px;height: 300px;background: #ccc;}
    
    .main{margin: 0 300px;height: 300px;background: #f00;}
    
    </style>
    
     
    
    <body>
    
    <div class="left">左列</div>
    
    <div class="main">中间</div>
    
    <div class="right">右列</div>
    
    </body>

    优点:比较简单容易,受到内部影响不大

    缺点:中间有最小宽度的限制,当宽度小到一定值,会发生元素重叠的情况

     

  2. margin负值方法,此方法要让中间内容放在最前面,并且要使用一个容器把其包起来,外层width设置为100%,随屏幕自适应,然后让外层元素整体浮动,内层为真正的内容,左右两列均采用margin负值定位,左列左浮动,然后设置margin-left为-100%,右列也设置左浮动,然后设置margin-left为自身的宽度的负值。代码如下:

    <style type="text/css">
    
    * {margin: 0;}
    
    .wrap {width: 100%;height: 300px;float: left;}
    
    .wrap .main {margin: 0 300px;height: 300px;background: #f00;}
    
    .left,.right {float: left;width: 300px;height: 300px;background: #ccc;}
    
    .left {margin-left: -100%;}
    
    .right {margin-left: -300px;}
    
    </style>
    
     
    
    <body>
    
    <div class="wrap">
    
    <div class="main">中间</div>
    
    </div>
    
    <div class="left">左列</div>
    
    <div class="right">右列</div>
    
    </body>

    优点:三列相互关联,受到内部影响不大

    缺点:比较难理解,相对其他比较复杂

     

  3. 浮动方法,此方法要让中间内容放在最后面,左列左浮动,右列右浮动,中间利用浮动的跟随性,实现三列自适应布局,代码如下:

    <style type="text/css">
    
    * {margin: 0;}
    
    .left {float: left;width: 300px;height: 300px;background: #ccc;}
    
    .right {float: right;width: 300px;height: 300px;background: #ccc;}
    
    .main {margin: 0 300px;height: 300px;background: #f00;}
    
    </style>
    
     
    
    <body>
    
    <div class="left">左列</div>
    
    <div class="right">右列</div>
    
    <div class="main">中间</div>
    
    </body>

    优点:简单易懂,代码简洁

    缺点:中间内容不能使用clear:both属性

    除了第一种绝对定位方法可以不在意左中右三列div的顺序,第二种margin负值和第三种浮动方法都需要注意左中右三列div的顺序,第二中方法需要给中间内容套一层父级div元素。以上就是我学习的三种三列自适应布局的方法。

推荐阅读