首页 > 解决方案 > 使用 Bootstrap 4 垂直堆叠最后一个 DIV 以填充/适合容器的其余部分

问题描述

我正在尝试使用 Bootstrap 4 创建一个响应式布局。我遇到的问题是,当两个 div 为较小的设备垂直包装时,顶部 div 似乎将下部 div 向下推超过父容器(请参阅下面的图像)。我希望较低的 div 适合容器,如何使用 Bootstrap 4 或最小的 css 来实现这一点?

我在第二个 div 的底部添加了一个黄色边框,以便我们可以看到推送。

大设备视图

小设备视图

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  width: 100%;
  overflow-x: hidden;
  overflow-y: hidden;
}

.bottom-border {
  border-bottom: 50px solid yellow;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <div class="container-fluid p-0 h-100">
    <div class="row h-100">
      <div class="col-md-8 bg-primary h-md-100 ">
        <div class="d-md-none text-center bg-primary">
          <h5>Left Section</h5>
        </div>
        <div class="d-none d-md-block m-3">
          <h1>Left Section</h1>
        </div>
      </div>
      <div class="col-md-4 h-100 text-center bg-danger bottom-border">
        <h4>Right Section</h4>
      </div>
    </div>
  </div>
</body>

标签: htmlcssbootstrap-4

解决方案


在您解释了边框高度的意义之后,现在我明白您的意思了,如前所述,您的h-100类是问题所在。

该类告诉元素使用其父级高度的 100%,因为您将该类放在主元素containerrow元素上,这两个使用全屏的高度,因为容器的父级是浏览器窗口,而行父级是容器.

当您在子 div 上使用相同的类时,在本例中为红色 div,它也会尝试使用其父级(行)的完整高度,但它不考虑内部的其他项目(蓝色 div ),如果您h-100从红色 div 中删除该类,那么它们中的每一个都将使用一半的可用空间。

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  width: 100%;
  overflow-x: hidden;
  overflow-y: hidden;
}

.bottom-border {
  border-bottom: 50px solid yellow;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<body>
  <div class="container-fluid h-100">
    <div class="row h-100 flex-column flex-md-row">
      <div class="col-md-8 bg-primary">
        <div class="d-md-none text-center bg-primary">
          <h5>Left Section</h5>
        </div>
        <div class="d-none d-md-block m-3">
          <h1>Left Section</h1>
        </div>
      </div>
      <div class="col-md-4 flex-grow-1 text-center bg-danger bottom-border">
        <h4>Right Section</h4>
      </div>
    </div>
  </div>
</body>


推荐阅读