品字布局设计

实现满屏品字布局的几种方案

问题

实现一个满屏的”品”字布局:上方一个元素水平居中,下方两个元素并排平分宽度。

解答

方案一:float 实现

<!DOCTYPE html>
<html>
<head>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    html, body {
      height: 100%;
    }
    /* 上方元素:宽度 50%,居中 */
    .top {
      height: 50%;
      width: 50%;
      margin: 0 auto;
      background: #f66;
    }
    /* 下方左侧元素 */
    .bottom-left {
      float: left;
      width: 50%;
      height: 50%;
      background: #6f6;
    }
    /* 下方右侧元素 */
    .bottom-right {
      float: left;
      width: 50%;
      height: 50%;
      background: #66f;
    }
  </style>
</head>
<body>
  <div class="top"></div>
  <div class="bottom-left"></div>
  <div class="bottom-right"></div>
</body>
</html>

方案二:flex 实现

<!DOCTYPE html>
<html>
<head>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    html, body {
      height: 100%;
    }
    body {
      display: flex;
      flex-wrap: wrap;
    }
    .top {
      width: 100%;
      height: 50%;
      display: flex;
      justify-content: center;
    }
    /* 上方内容区域 */
    .top-content {
      width: 50%;
      height: 100%;
      background: #f66;
    }
    .bottom-left,
    .bottom-right {
      width: 50%;
      height: 50%;
    }
    .bottom-left {
      background: #6f6;
    }
    .bottom-right {
      background: #66f;
    }
  </style>
</head>
<body>
  <div class="top">
    <div class="top-content"></div>
  </div>
  <div class="bottom-left"></div>
  <div class="bottom-right"></div>
</body>
</html>

方案三:grid 实现

<!DOCTYPE html>
<html>
<head>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    html, body {
      height: 100%;
    }
    body {
      display: grid;
      /* 两列,每列 50% */
      grid-template-columns: 1fr 1fr;
      /* 两行,每行 50% */
      grid-template-rows: 1fr 1fr;
    }
    .top {
      /* 横跨两列,居中显示 */
      grid-column: 1 / 3;
      display: flex;
      justify-content: center;
      background: transparent;
    }
    .top-content {
      width: 50%;
      background: #f66;
    }
    .bottom-left {
      background: #6f6;
    }
    .bottom-right {
      background: #66f;
    }
  </style>
</head>
<body>
  <div class="top">
    <div class="top-content"></div>
  </div>
  <div class="bottom-left"></div>
  <div class="bottom-right"></div>
</body>
</html>

关键点

  • 上方元素用 margin: 0 auto 或 flex/grid 居中
  • 下方两元素各占 50% 宽度,可用 float、flex 或 cm8n4 实现
  • 满屏需要设置 html, body { height: 100% }
  • 清除默认 margin 和 padding 避免出现滚动条
  • grid 方案最简洁,但需考虑兼容性