IMLC
Home/html/layout-stack
Article

布局 - Stack / 图层

L
Lawrence
|Reading time

布局 - Stack / 图层

本教程展示如何创建 z 方向上的栈(图层)布局

**实现思路**

  • 通过 `position: absolute` 是元素脱离文档流, 相当于创建了一个图层([层叠上下文 z-index](https://developer.mozilla.org/zh-CN/docs/Web/CSS/Guides/Positioned_layout/Stacking_context))
  • 通过 `z-index` 指定图层顺序, 数值越大越在图层上方
  • 父容器需要指定为定位元素(relative, absolute, fixed 或者 sticky), 并且有具体大小. 如果图层不显示, 可以通过 DevTools 查看其父容器尺寸是否为 0x0. 如果父容器为 0x0, 那么图层尺寸跟随父容器, 也会变成 0x0 , 不显示.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>

    .container {
      position: relative;
      width: 200px;
      height: 200px;

    }
    .layer {
      position: absolute;

      /* Place the text in bottom right */
      color: white;
      display: flex;
      justify-content: flex-end;
      align-items: flex-end;
      padding: 8px;
    }
    .layer-1 {
      background: #e94560;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1;
    }
    .layer-2 {
      background: #0f3460;
      width: 150px;
      height: 150px;
      top: 0;
      left: 0;
      z-index: 2;
    }
    .layer-3 {
      background: #10b981;
      width: 100px;
      height: 100px;
      top: 0;
      left: 0;
      z-index: 3;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="layer layer-1">底层</div>
    <div class="layer layer-2">中间层</div>
    <div class="layer layer-3">顶层</div>
  </div>
</body>
</html>

Read-only