【问题标题】:How can I have the first row at the top and the second row vertically centered?我怎样才能让第一行在顶部,第二行垂直居中?
【发布时间】:2021-09-17 11:32:53
【问题描述】:

我正在使用 Bootstrap 5,我试图让第一行位于页面顶部,第二行占据视口的其余部分,并使其内容垂直居中而没有滚动条(假设视口足够高)。这是基本代码

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="container min-vh-100">
  <div class="row">
    <div class="col-12 col-md-2">
      Content
    </div>
    <div class="col-12 col-md-10">
      Content
    </div>
  </div>

  <div class="row min-vh-100 align-items-center">
    <div class="col-12 col-lg-6">
      Content
    </div>
    <div class="col-12 col-lg-6">
      Content
    </div>
  </div>
</div>

但是,第二行确实正确地将其内容居中,因为我使用的是 min-vh-100 类,它会产生滚动条(删除第一行会使滚动条按预期消失)。将第二行的 min-vh-100 更改为 h-100 类并没有帮助(实际上使事情变得更糟)。问题似乎是如何告诉第二行占据父级剩余高度的 100%,而不是视口高度的 100%。

【问题讨论】:

  • “垂直居中”和“占用剩余空间”并不是一回事。前者是位置,后者是指尺寸。你应该修改以明确你所追求的。

标签: html css twitter-bootstrap vertical-alignment


【解决方案1】:

您需要容器上的 d-flexflex-column 类。然后,不要在第二行强制高度,而是使用flex-fill 让它使用剩余空间。固定大小应该是最后的手段。

https://getbootstrap.com/docs/5.0/utilities/flex

.row:first-child {
  background: thistle;
}

.row:last-child {
  background: moccasin;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="container min-vh-100 d-flex flex-column">
  <div class="row">
    <div class="col-2">
      Content
    </div>
    <div class="col-10">
      Content
    </div>
  </div>

  <div class="row flex-fill align-items-center">
    <div class="col-6">
      Content
    </div>
    <div class="col-6">
      Content
    </div>
  </div>
</div>

【讨论】:

  • Bootstrap 容器默认不是 flexbox 有什么原因吗?这些行是,所以人们会假设容器也是。
  • 我想是因为大多数网站不会尝试适应视口——行高由内容决定。
猜你喜欢
  • 2019-02-25
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 2018-03-11
相关资源
最近更新 更多