【问题标题】:How to stack flex children over each other如何将flex子元素堆叠在一起
【发布时间】:2022-01-10 01:03:10
【问题描述】:
我想在不使用固定宽度和高度的情况下将两个框(和重叠)放在屏幕中间。
最后,我想使用 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>
【问题讨论】:
标签:
html
css
bootstrap-4
flexbox
centering
【解决方案1】:
您可能不会使用 Bootstrap 4 来实现这一点,因为它不提供 CSS 网格类。这是一些应该做的自定义 CSS。
见https://css-tricks.com/snippets/css/complete-guide-grid
如果您碰巧可以选择升级到 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>