You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS如何实现多个div重叠并让侧边div垂直居中

布局问题解决方案

修改后的完整可运行代码如下:

<!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>布局Demo</title>
  <style>
    .maind {
      margin: 0px auto;
      width: 90%;
      padding: 10px;
      height: 900px;
      background-color: rgb(9, 252, 9);
      position: relative;
    }

    .fdiv {
      margin: 30px auto -50px;
      width: 25%;
      padding: 10px;
      height: 100px;
      background-color: rgb(10, 233, 222);
      border: 2px solid red;
      position: relative;
      z-index: 2;
    }

    .sdiv {
      width: 55%;
      height: 600px;
      background-color: #ffff00ec;
      position: relative;
      z-index: 1;
    }

    .tdiv {
      margin: -50px auto 0;
      width: 25%;
      padding: 10px;
      height: 100px;
      background-color: rgb(10, 233, 222);
      border: 2px solid red;
      position: relative;
      z-index: 2;
    }

    p {
      text-align: center;
    }

    .wrap {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
    }

    .wr1 {
      width: 25%;
      height: 100px;
      background-color: rgb(10, 233, 222);
      border: 2px solid red;
    }
  </style>
</head>
<body>
  <div class="maind">
    <div class="fdiv">
      <p>Some content here...</p>
    </div>
    <div class="wrap">
      <div class="wr1">
        <p>Some content here..</p>
      </div>
      <div class="sdiv">
        <p>Some content here..</p>
      </div>
      <div class="wr1">
        <p>Some content here...</p>
      </div>
    </div>
    <div class="tdiv">
      <p>Some content here..</p>
    </div>
  </div>
</body>
</html>

核心修改说明:

  • 给.wrap新增align-items: center属性,实现flex布局下子元素垂直居中对齐,解决左右两侧蓝色div无法和黄色主div垂直居中的问题。
  • 给上下蓝色div.fdiv、.tdiv添加position: relative和z-index: 2,给黄色主div.sdiv添加position: relative和z-index: 1,保证上下蓝色div的层级高于黄色主div,解决重叠时层级异常的问题。
  • 调整.fdiv的margin值为30px auto -50px,.tdiv的margin值为-50px auto 0,通过负margin让上下蓝色div向中间黄色主div偏移,实现期望的重叠效果。

内容的提问来源于stack exchange,提问作者user16639239

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:15:02