如何将 flex 子级堆叠在一起

How to stack flex children over each other

我想在不使用固定宽度和高度的情况下将两个框(和重叠框)居中放置在屏幕中间。

最后,我想使用 CSS 转换使框 1 消失并显示框 2(在单击按钮后)。

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />

<div class="container w-100 bg-dark" style="height: 400px;">
  <div class="d-flex justify-content-center align-items-center bg-light h-100">
    <div class="bg-white px-4 py-4 rounded shadow" style="z-index: 1">
      <p>
        Box 1
      </p>
    </div>
    <div class="bg-white px-4 py-4 rounded shadow" style="z-index: 2">
      <p>
        Box 2: More Content <br>
        Lorem Ipsum
      </p>
    </div>
  </div>
</div>

您可能无法使用 Bootstrap 4 完成此操作,因为它不提供 CSS 网格 类。这是一些应该做的自定义 CSS。

https://css-tricks.com/snippets/css/complete-guide-grid

如果您碰巧可以选择升级到 Bootstrap5,it does CSS grid

setInterval(function() {
  $('p:first-child').fadeIn(3000);
  $('p:last-child').fadeOut(3000);

  setTimeout(function() {
    $('p:first-child').fadeOut(3000);
    $('p:last-child').fadeIn(3000);
  }, 3000);
});
.grid-box {
  display: grid;
  grid-template-columns: repeat(1, [col] 100px);
  grid-template-rows: repeat(1, [row] auto);
}

.top,
.bottom {
  grid-column: col 1 / span 1;
  grid-row: row 1;
  z-index: 20;
  background: #fff;
}

.bottom {
  z-index: 30;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />

<div class="container w-100 bg-dark" style="height: 150px;">
  <div class="d-flex justify-content-center align-items-center bg-light h-100">
    <div class="bg-white px-4 py-4 rounded shadow grid-box">
      <p class="top">
        Box 1
      </p>

      <p class="bottom">
        Box 2: More Content <br> Lorem Ipsum
      </p>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>