How to stack flex children over each other

Viewed 71

I want to center both boxes (and overlapping) in the middle of the screen without using a fixed width and height.

At the end I want to use CSS transitions to make box 1 disappear and show box 2 instead (after clicking a button).

<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>

1 Answers

You probably won't pull this off with Bootstrap 4, as it doesn't provide CSS grid classes. Here's some custom CSS that should do.

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

If you happen to have the option of upgrading to Bootstrap 5, 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>

Related