三列布局:圣杯布局、双飞翼布局

108 阅读1分钟

实例代码地址

左右两边固定,中间自适应

  1. 圣杯布局
  2. 双飞翼布局
  • 相同点:
  1. 将盒子设置为左浮动,HTML盒子加载顺序为: content(中间)->left(左栏)->right(右栏)
  2. 中间容器100%宽度,随页面宽度变化而变化
  3. 用左边距将左右容器覆盖在中间容器上
  • 不同点: 所有容器拉到同一行后:
  1. 圣杯 -> 利用相对定位将左右容器移出中间容器 -> 最外层容器添加padding,防止覆盖中间容器;
  2. 双飞翼 -> 中间容器再套一层inner,内容在inner中显示 -> 内层加padding,使得不会被左右容器覆盖

布局结构区别示意图

image.png

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>圣杯布局</title>
  </head>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .left,
    .right {
      background-color: blue;
      width: 200px;
      height: 500px;
    }

    .content {
      background-color: red;
      /* 撑满容器 */
      width: 100%;
      height: 500px;
    }

    .container div {
      float: left;
    }

    .container {
      height: 1000px;
      padding: 0 200px;
    }

    .left {
      /* 将left容器拉到第一行,相对于centent容器向左移动100% */
      margin-left: -100%;
      /* 再向左移动left容器本身宽度 */
      position: relative;
      left: -200px;
    }

    .right {
      /* 将right容器拉到第一行,相对于centent容器向左移动right容器宽度 */
      margin-left: -200px;
      /* 相对于right自身位置向左再移动right容器宽度 */
      position: relative;
      left: 200px;
    }
  </style>
  <body>
    <div class="container">
      <div class="content">content</div>
      <div class="left">left</div>
      <div class="right">right</div>
    </div>
  </body>
</html>

image.png

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>双飞翼布局</title>
  </head>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .left,
    .right {
      background-color: blue;
      width: 200px;
      height: 500px;
      float: left;
    }

    .content {
      background-color: red;
      width: 100%;
      height: 500px;
      float: left;
    }

    .content-inner {
      margin: 0 200px;
      height: 500px;
    }

    .left {
      margin-left: -100%;
    }

    .right {
      margin-left: -200px;
    }
  </style>
  <body>
    <div class="container">
      <div class="content">
        <div class="content-inner">content-inner</div>
      </div>
      <div class="left">left</div>
      <div class="right">right</div>
    </div>
  </body>
</html>

image.png