css 经典布局之圣杯布局(左右固定,中间自适应)

css 圣杯布局在国内又叫做双飞翼布局,这种布局的特点是左右两边的宽度固定,中间的宽度自适应,同理也可以实现左边固定,右边自适应,反之亦然。

注: 我不做 IE6 兼容已经很多年了。

第一种方式: 使用 margin

这种方式的原理是三个区块都设置成左浮动,中间的区块宽度 100%,调整左右区块的 margin 实现三栏布局。
html:

<div class="container">
  <div class="column main">
    <div class="main-wrap">main content</div>
  </div>
  <div class="column left">left</div>
  <div class="column right">right</div>
</div>

css:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    .container {
      margin: 0 auto;
    }
    /* clearfix */
    .container:after {
      clear: both;
      content: '\0020';
      height: 0;
      display: block;
    }
    .column {
      float: left;
      position: relative;
    }
    .left {
      background: #666;
      width: 150px;
      min-height: 400px;
      margin-left: -100%;
    }
    .main {
      width: 100%;
      background: #333;
      min-height: 400px;
    }
    .main-wrap {
      margin: 0 200px 0 150px;
      min-height: 400px;
    }
    .right {
      width: 200px;
      background: #999;
      min-height: 400px;
      margin-left: -200px;
    }

第二种方式: 使用绝对定位

 这种方式的原理是父容器设置宽度 100% ,左右内边距(padding)为左右区块的宽度,左区块设置 margin-left 为自身宽度,右区块使用绝对定位将其定位到右上。

html:

<div class="container">
  <div class="left">left</div>
  <div class="main">main</div>
  <div class="right">right</div>
</div>

css:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  max-width: 1200px;
  padding: 0 200px 0 150px;
  margin: 0 auto;
  position: relative;
}
.left {
  background: #666;
  float: left;
  width: 150px;
  margin-left: -150px;
  min-height: 400px;
}
.main {
  width: 100%;
  background: #333;
  min-height: 400px;
}
.right {
  width: 200px;
  background: #999;
  min-height: 400px;
  position: absolute;
  top: 0;
  right: 0;
}

 

posted on 2015-08-23 14:24  SherryIsMe  阅读(259)  评论(0编辑  收藏  举报

导航