当 div 高度小于浏览器高度时如何垂直居中 div (Bootstrap)

3

我正在使用CSS Bootstrap 4,其中包含多列放置在容器内的行。根据屏幕大小,这些列可以堆叠在彼此之上,并使容器变得更高,有时会超出屏幕可显示的范围并需要滚动。我似乎无法找到一种方法来同时满足以下两个条件:

  • 如果容器比浏览器窗口高度短,则将容器居中放置在屏幕中央
  • 如果容器比浏览器窗口高度更高,则不要将容器居中放置(以便它不会超出屏幕)

我已经有了以下代码,可以将容器居中放置,但是当文本行数变得比屏幕更高时,由于.centered,它会直接超出屏幕范围,而不能像普通页面一样滚动。

以下是我的HTML代码:

<div class="container centered" style="width: 100%">
    <div class="row justify-content-center">
            <div class="col-8" id="main">
                Text<br>
                Text<br>
                Text<br>
                <!-- Any number of more lines may be added here -->
            </div>
    </div>
</div>

我的CSS如下所示:
html,
body {
  width: 100%;
}

body {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: rgb(0, 0, 0);
}

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#main {
  background-color: rgb(30,29,38.3);
  border-radius: 6px;
  box-shadow: 0 0 30px rgb(25, 25, 35);
}

CSS没有容器查询,只有媒体查询。这不能通过CSS解决,只能使用Javascript。 - connexo
3个回答

0

我相信这个解决方案会解决你的问题(我只使用了CSS),你可以在第一行和最后一行之间添加文本行来测试我的解决方案:

*{
  box-sizing: border-box;
}
body {
  /* improtant lines */
  display: grid;
  align-items: center;
  min-height: 100vh;
  overflow-y: auto;
  /* improtant lines */
  background-color: rgb(0, 0, 0);
  margin: 0;
}

.centered {
  /* improtant lines */
  display: grid;
  align-items: start;
  /* improtant lines */
  padding: 1em 2em;
}

#main {
  background-color: rgb(30,29,38.3);
  border-radius: 6px;
  box-shadow: 0 0 30px rgb(25, 25, 35);
  color: white;
  padding: 1em;
}
<div class="centered">
      <div id="main">
          First Text<br>
          Text<br>
          Text<br>
          Text<br>
          Text<br>
          Text<br>
          Text<br>
          Last Text<br>
      </div>
</div>

解释:我在主体中添加了一个网格显示,并使其子元素垂直居中,然后在“.centered”元素本身上添加了一个网格显示,并将其项目垂直对齐到开始位置。

0

<body class="d-flex justify-content-center align-items-center"></body>

或者

     `.body
      { 
        display:flex;
        justify-content:center;
        align-items: center; 
        height: 100vh;
      }`

-1

centered 的固定位置会将其从正常页面流中移除,这会导致页面无法滚动。使用以下方法更容易居中:

body {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  background-color: rgb(0, 0, 0);
  justify-content: center;
  min-height: 100vh;
}

https://codeply.com/p/tUejIBKi12

或者,使用 Bootstrap 类实现相同的结果:

<body class="d-flex align-items-center justify-content-center min-vh-100">
    <div class="container">
        I'm centered...
    </div>
</body>

在StackOverflow上不鼓励使用jsfiddle、codepen等外部代码托管网站。请使用SO提供的代码片段功能。 - connexo
你说得对,这方面没有官方声明。我非常赞同应该有一个声明,我和这个链接中的人持相同观点:https://meta.stackoverflow.com/a/302293/3744304。 - connexo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接